Consuming Your Own API In Laravel
There have been so many times that I create a new Laravel application and I start putting routes into my
routes\api.php file and try to hit that route and get the dreaded
This message seems so counter-intuitive since Laravel ships with code that makes it seem like it would already be taken care of for you. Like this in
This code puts the required CSRF token into the headers of axios to authenticate your request. But this isn’t enough to get up and running. We’ll use Laravel Passport to finish the job.
Side Note: This is the best/fastest way I have figured out. If you have a different/better way to get it setup please let me know!
Passport has a lot of instructions and we’ll only need the first part, and the last part. You can go to the docs and follow the first part (Installation) on your own if you wish, but for ease of use I’m just going to cover the steps quickly here.
First, we’ll pull in the package with composer:
composer require laravel/passport
Then we’ll register the service provider in the
providers array of our
Next we’ll need to migrate our database:
php artisan migrate
Then we need have passport setup encryption keys and whatnot:
php artisan passport:install
Then add the
HasApiTokens trait to your
App\User model. Change the line
use Notifiable; to
use HasApiTokens, Notifiable; and make sure to import the class
Passport::routes() in the
boot method of your
And the last part of setting up Passport is changing the
api section of your
config/auth.php file to use the
passport driver instead of
Now we can move onto the last piece. Which is at the bottom of the documentation for Passport.
CreateFreshApiToken middleware to your
web middleware group in
Once you’ve done that, you’re golden!