If you need to use Directus with Laravel then this guide will take you through the steps needed to get connected in just a few minutes.
The general idea is to use a composer package to interact with Directus. We’ll register it in our AppServiceProvider which means we can call a pre-configured instance anywhere in our app using dependency-injection.
In Directus
- It’s advisable to create a new role for your Laravel Application. To make it easy to track I give it the name ‘laravel-app’
- Create a new user for your Laravel Application and assign it the new Role you just created
- On the Edit User screen, find the ‘Token’ field. Generate a token and make a note of it somewhere
In Laravel
- Now switch to your Laravel app. For this integration, I’m using a composer package from https://github.com/alantiller/directus-php-sdk
- Install the package:
composer require alantiller/directus-php-sdk
- In your
.env
file add the following:
DIRECTUS_URL=https://directus.example.com
DIRECTUS_TOKEN=-YOURTOKEN
- Replace the Url with your actual Directus URL
- Replace YOURTOKEN with the Token you generated for your Laravel user in Directus
- In config/services.php add the following:
'directus' => [
'url' => env('DIRECTUS_URL'),
'token' => env('DIRECTUS_TOKEN'),
],
In app/providers/AppServiceProvider.php add the following to the register()
method
$this->app->singleton(Directus::class, function ($app) {
$directus = new Directus($app['config']['services']['directus']['url'],'');
$directus->auth_token($app['config']['services']['directus']['token']);
return $directus;
});
In your code you’ll be able to now use Directus with the standard dependency injection. You can find examples on how to use the alantiller/directus-php-sdk package on Github.
Example:
php artisan make:command DirectusTest
In the handle
method of the generated command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class DirectusTest extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'directus:test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*
* @return int
*/
public function handle(\Slations\DirectusSdk\Directus $directus)
{
dd($directus->users_me());
}
}
Call the command:
php artisan directus:tset
The output should show you details of the Laravel App user you added on Directus. Once it’s working delete the command.
This is all it takes to have a fully working Directus integration with Laravel. The package does most of the work, but registering it in your AppServiceProvider means you’ll get a connected instance whenever you need to use it instead of having to instantiate it.
Note that this application uses an application token which is tied to a single user. If you need multi-user support then the package supports login
so you can authenticate users and use their auth token.