Effortless Notion integrations with Laravel

Overview

Laravel Notion API

Effortless Notion integrations with Laravel

Latest Version on Packagist Total Downloads

This package provides a simple and crisp way to access the Notion API endpoints, query data and update existing entries.

Installation

You can install the package via composer:

composer require fiveam-code/laravel-notion-api

Authorization

The Notion API requires an access token and a Notion integration, the Notion documentation explains how this works. It's important to grant access to the integration within your Notion account to enable the API access.

Add your Notion API token to your .env file:

NOTION_API_TOKEN="$YOUR_ACCESS_TOKEN"

Usage

Head over to the Documentation of this package.

🔥 Code Examples to jumpstart your Notion API Project

Basic Setup

use FiveamCode\LaravelNotionApi\Notion;
use Illuminate\Support\Collection;
use FiveamCode\LaravelNotionApi\Query\Sorting;
use FiveamCode\LaravelNotionApi\Query\Filter;

// Setup basic API connection
$notion = new Notion();
$notion->v1();

Fetch Page Information

// Returns a specific page
$notion->pages()->find($yourPageId);

Query Database

// Queries a specific database and returns a collection of pages (= database entries)
$sortings = new Collection();
$filters = new Collection();

$sortings
  ->add(Sorting::propertySort("Ordered", "ascending"));
$sortings
  ->add(Sorting::timestampSort("created_time", "ascending"));

$filters
  ->add(Filter::textFilter("title", ["contains" => "new"]));
// or
$filters
  ->add(Filter::rawFilter("Tags", ["multi_select" => ["contains" => "great"]]));
  
$notion
  ->database($yourDatabaseId)
  ->filterBy($filters) // filters are optional
  ->sortBy($sortings) // sorts are optional
  ->limit(5) // limit is optional
  ->query(); 

Testing

vendor/bin/phpunit tests

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Laravel Package Boilerplate

This package was generated using the Laravel Package Boilerplate.

Comments
  • Rollup that refers to an empty Select property throws exception during database query

    Rollup that refers to an empty Select property throws exception during database query

    Describe the bug

    When using the Notion::database() method to retrieve pages in a database, a HandlingException is thrown if it encounters a Rollup that refers to a Select, and that Select is empty.

    The exception is thrown inside FiveamCode\LaravelNotionApi\Entities\Properties\Select::fillFromRaw(). Exception message:

    "The property-type is select, however the raw data-structure does not reprecent this type. Please check the raw response-data."

    To Reproduce

    Laravel 8.60, OS MacOS 11.6 (Bug Sur), PHP 8.0.14.

    1. Create 2 databases in Notion, DB1 and DB2.
    2. In DB1, create a Select property titled "Select". Enter a couple of options.
    3. In DB2, create a Relation to DB1. Call it "Relation".
    4. In DB2, create a Rollup that uses the relation to DB1, and its Select property. Call it "Rollup".
    5. Create a row in DB1 but leave the Select empty. Title it "A".
    6. Create a row in DB2, Title it "X", and select "A" in its Relation property.

    Now use the following code to read the DB2 database:

    $notion = new Notion(secret_key);
    $results = $notion->database(id_for_DB2)->query();
    

    Expected behavior

    All rows from DB2 should be returned in $results. Instead, HandlingException is thrown with the message

    "The property-type is select, however the raw data-structure does not reprecent this type. Please check the raw response-data."

    bug 
    opened by farez 4
  • RichText function for Notion Page

    RichText function for Notion Page

    Hey, I have some Notion records (pages) where they have properties but also have this text inside the page: image

    Reading the Notion API documentation I figured out this is a rich text https://developers.notion.com/reference/rich-text however I am unable to find how to use it..

    Do you know if this is supported by the Notion API or not? Because I saw in your code you already have created a RichText property but couldn't find how to call that function.. Thanks!

    enhancement 
    opened by vgavrilovikj 4
  • getNextCursor does not exist using Laravel

    getNextCursor does not exist using Laravel

    Hey hey,

    hope this is not a newbie issue. First of all thanks for the amazing job. I'm having some issues with pagination.

    I'm using the package within laravel. When querying a database it seems that the returned results are a Laravel Collection and the method getNextCursor doesn't exist. here's the error I'm getting:

     BadMethodCallException 
    
      Method Illuminate\Support\Collection::getNextCursor does not exist.
    
      at vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php:113
        109â–•      */
        110â–•     public function __call($method, $parameters)
        111â–•     {
        112â–•         if (! static::hasMacro($method)) {
      ➜ 113▕             throw new BadMethodCallException(sprintf(
        114â–•                 'Method %s::%s does not exist.', static::class, $method
        115â–•             ));
        116â–•         }
        117â–• 
    
    

    and my sample code:

    
                if(!$offset)
                {
                    $tasks=$notion->database($databaseId)
                    ->sortBy($sortings)
                    ->limit(5)
                    ->query()
                    ->asCollection();
                } else {
                    $tasks=$notion->database($databaseId)
                    ->sortBy($sortings)
                    ->offset($offset)
                    ->limit(5)
                    ->query()
                    ->asCollection();
                }
    
                $offset= $tasks->getNextCursor();
    

    Any help would be hugely appreciated :)

    opened by DivByZeroIT 3
  • Page Creation example doesn't work

    Page Creation example doesn't work

    Hi. Thanks for this great package!

    Describe the bug I'm trying to create a page in a database, and following the example here: https://5amco.de/docs/0.5.0/examples/update_create/create_page

    Basically this didn't work because the method createInDatabase doesn't exist in the Notion class: Notion::createInDatabase($databaseId, $page);

    To Reproduce

    Try to run Notion::createInDatabase($databaseId, $page);

    Laravel: 8.56

    Expected behavior

    A page is successfully created in Notion.

    Exceptions

    None.

    Additional context

    I did notice that the Pages class does have the createInDatabase, I tried the following code, but that returned a "Bad Request" error.

    use FiveamCode\LaravelNotionApi\Notion;
    use FiveamCode\LaravelNotionApi\Entities\Page;
    
    $notion = new Notion($token);
    $page = new Page();
    $page->setTitle("Title", "Date Prop");
    $notion->pages()->createInDatabase($dbId, $page);
    
    documentation 
    opened by farez 3
  • Video Embed Block not rendered correctly

    Video Embed Block not rendered correctly

    Describe the bug When adding a Youtube Video to a newly created Notion page the block is correctly added with its caption, the origin link sends to the correct video in Youtube, but the youtube player is not rendered correctly: CleanShot 2022-09-23 at 07 55 06

    To Reproduce $newBlock = Video::create("https://www.youtube.com/watch?v=KLPZzf-wwlE",$video['title']); $notion->block($notionPage->getId())->append($newBlock);

    Bonus Quesion Is there a way to create the page using a template? :)

    Thank you so much for your hard work on this great library

    opened by DivByZeroIT 2
  • 65 rollup with empty select fix

    65 rollup with empty select fix

    fix: check if content is set for rollup properties

    • specific rollup properties can be null, which lead to issues of setting the content of the property
    • this fix checks the existence of content and skips setting the content, if it is null (e.g. empty selects, multi_selects etc.)
    • fixes issue: Rollup that refers to an empty Select property throws exception during database query
    fix 
    opened by johguentner 2
  • Retrieve database entries in the manually-sorted order

    Retrieve database entries in the manually-sorted order

    I'm trying to retrieve a simple list of pages in a database. In Notion, I have manually dragged and re-ordered these to be in a specific order.

    When I retrieve them simply as a collection...

    Notion::database($databaseId)->query()->asCollection();
    

    ... and loop through, they are not in the same order as in Notion.

    Yes I know I can specify explicit ordering, but I don't have any field/property that I can order on. My goal is to let the user manually drag to order items, and display them in that same order in my app.

    Is this possible?

    blocked by dependency 
    opened by jszobody 2
  • Choose wether time is displayed for date property in page

    Choose wether time is displayed for date property in page

    Is your feature request related to a problem? Please describe. At the moment when a Date property is added to a Page, it's automatically set with date and time, even if time is actually not needed.

    Describe the solution you'd like It would be awesome if we could choose wether to display time or not! Because displaying time in Notion when not needed is a bit "polluting".

    Describe alternatives you've considered In the meantime I make sure I set my Datetime with 0 in hours, minutes and seconds.

    Additional context What I would like: image Instead of: image

    bug enhancement 
    opened by rooselle 2
  • Syntax error when using PHP 7.4, due to use of union type.

    Syntax error when using PHP 7.4, due to use of union type.

    Describe the bug

    The union type float|int in the function definition of Filter::numberFilter() is flagged as a syntax error, when using PHP 7.4.

    Union types are only valid in PHP8.0 and above, but PHP 7.4 is being supported in composer.json.

    To Reproduce Call Filter::numberFilter() while using PHP 7.4.

    Expected behavior There should not be a syntax error.

    Exceptions This works fine in PHP8.0. So maybe remove all use of union types or make PHP8.0 the minimum requirement?

    Additional context None.

    bug 
    opened by farez 2
  • Cast startCursor to string

    Cast startCursor to string

    Without a cast, it will be sent as an object and Notion will return a 400 error:

    Bad Request: (validation_error) (body failed validation: body.start_cursor should be a string or `undefined`, instead was `{}`.)  
    
    opened by keithbrink 2
  • block creation + all new current blocks (+ tests for creation/fetch)

    block creation + all new current blocks (+ tests for creation/fetch)

    • implemented static creation-function for all modifiable blocks
    • implemented append-function to Block-Endpoint
    • implemented tests-function, in which all block-creation-functions are tested
    • added todo/warning for notion-version-change to test-function
    opened by johguentner 2
  • NotionException: Use status from http response #88 additions

    NotionException: Use status from http response #88 additions

    • add assertions for exception codes
    • change the FiveamCode\LaravelNotionApi\Exceptions\NotionException::instance method to use $payload['responseData']['status'] field if it exists in exception code. 0, otherwise.
    opened by danielh-official 4
  • Using rawFilter on a status property type returns a validation error

    Using rawFilter on a status property type returns a validation error

    Describe the bug

    When I use Filter::rawFilter to query a Notion database on a status property type, a validation error is returned.

    To Reproduce

    Set the filter and send the query:

    $filters = new Collection(); $filters->add(Filter::rawFilter("Status", ["status" => [Operators::EQUALS => "Ready"]] ));

    $notion = new Notion($access_token)

    $rows = $notion->database($id) ->filterBy($filters) ->sortBy($sortings) ->query() ->asCollection();

    Expected behavior

    A filtered results collection is returned.

    Exceptions

    Trace can be found here: https://flareapp.io/share/pPv1vqYm#F58

    Additional context

    Screenshot 2022-12-02 at 11 22 46 PM bug currently not supported 
    opened by farez 1
  • NotionException returns wrong code

    NotionException returns wrong code

    Describe the bug When a NotionException is thrown, the code is always 0.

    To Reproduce No reproduction needed. See code: https://github.com/5am-code/laravel-notion-api/blob/4f75db65b22cb600ffdfba14eab49b1ef36bee54/src/Exceptions/NotionException.php#L47-L51

    Expected behavior The exception should contain the HTTP Status code.

    Exceptions . Additional context .

    See my PR https://github.com/5am-code/laravel-notion-api/pull/88

    bug 
    opened by fschirinzi 0
  • Bug: Cursor converted to empty object

    Bug: Cursor converted to empty object

    Search-Endpoint while searching using a cursor is broken.

    Here it is correct: https://github.com/5am-code/laravel-notion-api/blob/4f75db65b22cb600ffdfba14eab49b1ef36bee54/src/Endpoints/Database.php#L70

    Bug: generates an empty array/object: https://github.com/5am-code/laravel-notion-api/blob/20a7fcc7cfce1a479a4218705a179d1d3f48d296/src/Endpoints/Search.php#L64

    Error message

    Bad Request: (validation_error) (body failed validation: body.start_cursor should be a string or `undefined`, instead was `{}`.)
    
    bug 
    opened by fschirinzi 0
  • Compound Filters

    Compound Filters

    I'd like to use the compound filters (currently a TODO comment) when querying a database. Specifically, I would like to use an "and" filter to add two filters at the same time.

    Really just opening the issue to give me a place to track it whenever it gets implemented - love this package thanks for all your excellent work on it.

    enhancement 
    opened by keithbrink 4
Releases(v0.8.0)
  • v0.8.0(Aug 1, 2022)

    What's Changed

    • Fix: Rollup with empty select in https://github.com/5am-code/laravel-notion-api/pull/68
      • ✅ Solved: If a Rollup Property had an empty select or multi_select, there was an error.
      • Fix for https://github.com/5am-code/laravel-notion-api/issues/65
    • polish/fix: control over 'includeTime' of Date in https://github.com/5am-code/laravel-notion-api/pull/69
      • ✅ Solved: If a Date Property has been set by creating or updating a Notion Page, the time was always included
      • Fix for https://github.com/5am-code/laravel-notion-api/issues/61
    • Feature/better pagination handling: add: better pagination handling in https://github.com/5am-code/laravel-notion-api/pull/73

    More Details in our docs: Docs - Changelog

    Full Changelog: https://github.com/5am-code/laravel-notion-api/compare/v0.7.0...v0.8.0

    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Mar 20, 2022)

    What's Changed

    • Now compatible with Laravel 9
    • Allow v9 of illuminate/support by @treonde in https://github.com/5am-code/laravel-notion-api/pull/63
    • Updated README.md by @farez in https://github.com/5am-code/laravel-notion-api/pull/62

    New Contributors

    • @treonde made their first contribution in https://github.com/5am-code/laravel-notion-api/pull/63
    • @farez made their first contribution in https://github.com/5am-code/laravel-notion-api/pull/62
    Source code(tar.gz)
    Source code(zip)
  • v0.6.2(Dec 28, 2021)

    What's Changed

    • Removed union types in method parameters (temporarily for PHP 7.4 support) and replaced them with corresponding type check (Syntax error when using PHP 7.4, due to use of union type. #51)
    • Changed Eloquent Collection Import to Support Collection (use Support\Collection instead of Eloquent\Collection #50)
    • Added StyleCI
    • Added PHP 8.1 and PHP 7.4 to Workflows

    New Contributors

    • @blessingefkt made their first contribution in https://github.com/5am-code/laravel-notion-api/pull/50

    Full Changelog: https://5amco.de/docs/0.6.0/changelog

    Source code(tar.gz)
    Source code(zip)
  • v0.6.1(Oct 18, 2021)

    • fix typo in operations (for query)
    • fix type-check issue in property LastEditedType
    • unnecessary class is removed
    • implementation for updating Blocks 🔥
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Sep 25, 2021)

    • We implemented a new approach for the Filter classes and start with Filter::textFilter and Filter::numberFilter. The other filter types will follow with time.
    • You're also able to create new blocks and append them in Notion!
    • More detailed database information can be fetched - Icon, cover, title and property-information is provided in the databases endpoint.
    • New block types have been added to the block classes

    For more information, check out the Changelog in our docs! https://5amco.de/docs/0.6.0/changelog

    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Aug 25, 2021)

    Check out https://5amco.de/docs/0.5.0/installation for new features and code examples 🔥

    • Added Modifiable contract to set-able properties
    • implement notion block types as classes
    • add url to page
    • implemented tests for blocks-endpoint
    • final tweaks and tests
    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Jun 19, 2021)

  • v0.3.1(May 30, 2021)

    v0.3.1 Patch Release

    Changes in the Notion API

    As of June 1st, the Notion API requires an additional version parameter in the HTTP header starting with new integrations. Old integrations will still work with our v0.3.0 for some time, but you should consider updating soon. For more information, visit Notions documentation.

    Deprecation notice

    The methodNotion::setToken() has now a »deprecated« flag for usage outside of the Notion class due to the new constructor and the changed version requirements. The methods visibility will be set to private in the next release (0.4.0). The Token should be stored in the projects .env file or must be provided via the constructor if the Facade is not used (not recommended).

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(May 24, 2021)

  • v0.2.0(May 15, 2021)

    • moved documentation from notion to 5amco.de/docs
    • added properties (of pages) as entities + added usage-example to documentation
    • refactored namespaces within entities
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0-alpha(May 14, 2021)

Owner
5amcode
Resources written in the morning hours and beyond.
5amcode
Laravel package to use the notion API

Package to work with Notion API from Laravel This package helps you to use the notion API from Laravel. Installation You can install the package via c

64 Robots 11 Jun 6, 2021
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Erik C. Forés 31 Dec 18, 2022
Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Sam Rapaport 46 Oct 1, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022
Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

Octohook 13 May 16, 2022
Laravel Sanctum support for Laravel Lighthouse

Lighthouse Sanctum Add Laravel Sanctum support to Lighthouse Requirements Installation Usage Login Logout Register Email Verification Forgot Password

Daniël de Wit 43 Dec 21, 2022
Bring Laravel 8's cursor pagination to Laravel 6, 7

Laravel Cursor Paginate for laravel 6,7 Installation You can install the package via composer: composer require vanthao03596/laravel-cursor-paginate U

Pham Thao 9 Nov 10, 2022
A package that uses blade templates to control how markdown is converted to HTML inside Laravel, as well as providing support for markdown files to Laravel views.

Install Install via composer. $ composer require olliecodes/laravel-etched-blade Once installed you'll want to publish the config. $ php artisan vendo

Ollie Codes 19 Jul 5, 2021
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

null 686 Dec 28, 2022
Laravel Jetstream is a beautifully designed application scaffolding for Laravel.

Laravel Jetstream is a beautifully designed application scaffolding for Laravel. Jetstream provides the perfect starting point for your next Laravel application and includes login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management.

The Laravel Framework 3.5k Jan 8, 2023
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Hussein Feras 52 Jul 17, 2022
A Laravel extension for using a laravel application on a multi domain setting

Laravel Multi Domain An extension for using Laravel in a multi domain setting Description This package allows a single Laravel installation to work wi

null 658 Jan 6, 2023
Example of using abrouter/abrouter-laravel-bridge in Laravel

ABRouter Laravel Example It's a example of using (ABRouter Laravel Client)[https://github.com/abrouter/abrouter-laravel-bridge] Set up locally First o

ABRouter 1 Oct 14, 2021
Laravel router extension to easily use Laravel's paginator without the query string

?? THIS PACKAGE HAS BEEN ABANDONED ?? We don't use this package anymore in our own projects and cannot justify the time needed to maintain it anymore.

Spatie 307 Sep 23, 2022
Laravel application project as Sheina Online Store backend to be built with Laravel and VueJS

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Boas Aditya Christian 1 Jan 11, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023