In the previous article Laravel api integration & configuration, we have successfully set up a Passport package in a fresh Laravel application. Now in this article, we are going to create API using the passport and we will protect all API routes and can be accessed If the user passes bearer token in each API request, otherwise the user can’t get any response. Php artisan migrate. Next, you should run the passport:install command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create 'personal access' and 'password grant' clients which will be used to generate access tokens: php artisan passport:install.
This is an article which is specifically written to generate key used in a Laravel web-based application project. The key generated is very special for several features which is needed by the Laravel web-based application itself. It is important because the key is going to be used further for generating cookies and even password across the application. It is actually generated a 32-length of random string.
Actually, it is going to be automatically generated upon the creation of the Laravel web-based application using composer utility or command which is represented with ‘composer create-project laravel/laravel’ command.
The key generated by typing a command which is executed as follows :
So, the command itself will sets the APP_KEY value in your .env file. On the other hand, if the Laravel web-based project is created by using a version control system like git to manage it for further usage, for an example calling git push to be able to push the source to a certain repository, it will definitely push a copy of the Laravel project to wherever it is going, but will not include the existing .env file . So, in order to run the project after cloning the project using git clone, it must be manually execute ‘php artisan key:generate’ for the application itself to function correctly.
But the command will failed as shown below :
This is a command which is needed to be carried out by a specific user account. It is might be the permission which is needed to write the .env file doesn’t fit enough. Only specific file is allowed to write or to modified the .env file since executing the command will actually insert a certain key value generated by the command to a specific file named ‘.env’. Try to re-execute the command and in the following output, it is executed using ‘root’ account as shown below :
The generated key can actually be viewed in the file .env as shown below for an example :
To generate the key, make sure that the entry in config/app.php which is defining the cipher used and the location of the exact 32 characters string will be inserted.
Laravel JSON API is a library for creating JSON:API backends using the Laravel application framework.
To try it out, let’s create a web service for rating dishes at restaurants. We’ll call it “Opinion Ate”.
First, we’ll need the following installed to use Laravel:
- PHP
- The
composer
command - The
laravel
command - A MySQL database
If you’re new to Laravel, one easy way to get it up and running is to use Laravel Homestead, a virtual machine pre-configured for Laravel development. This guide will assume you’re using Homestead; if not, make the necessary adjustments.
Edit your Homestead.yml
file to map a folder on your host machine to the Vagrant VM; this will make it easy to edit the files in your editor of choice:
After making this change, within your Homestead
folder run vagrant provision
to apply this configuration.
Connect to Homestead with vagrant ssh
, then create a new Laravel app:
Then, back in your Homestead.yml
file, configure this app to be shown at a certain domain name:
Make sure not to forget the /public
on the end.
Run vagrant provision
once more to apply this configuration. Finally, on your host machine, edit your /etc/hosts
file to point the domain name you configured to your local machine
Let’s make sure our app is up and running. Go to http://opinion-ate.test
in a browser. You should see the “Laravel” page with links to “Documentation”, “Laracasts”, and other things.
One last bit of configuration: check the .env
file to make sure your database connection is correct. With Homestead, update it to match the following:
Models
Laravel persists data to the database using classes called Eloquent models. Laravel JSON API uses the same models, so to start building our app we’ll create models in the typical Laravel way.
First let’s create a model representing a restaurant. If you aren’t already connected to Homestead, run vagrant ssh
, go into the opinion-ate
directory, and stay connected for the rest of the tutorial. Then, run the following command:
You’ll see output like the following:
The generator created a number of files; let’s take a look at a few of them. First, open the file in database/migrations
that ends with _create_restaurants_table.php
— the date on the file will be different than mine, showing the time you ran the command.
This file contains a migration, a class that tells Laravel how to make a change to a database. Schema::create()
will create the restaurants
table. The function passed to Schema::create()
will be passed the argument $table
, representing a table. It’s already set to create an id
and timestamps
. Let’s add a few additional columns:
The restaurants
table hasn’t actually been created yet; the migration file just records how to create it. You can run it on your computer, when a coworker pulls it down she can run it on hers, and you can run it on the production server as well. Run the migration now with this command:
If your database connection info is correct, you should see the following output, including a few other migrations Laravel creates by default:
Next let’s look at the app/Models/Restaurant.php
file created:
That’s…pretty empty. We have a Restaurant
class that inherits from EloquentModel
and adds a HasFactory
trait, but nothing else. This represents a Restaurant record, but how does it know what columns are available? Laravel will automatically inspect the table to see what columns are defined on it and make those columns available. We do need to add one bit of configuration: the fields that are allowed to be assigned-to by end users:
Now let’s set up the model for a dish itself.
Add the following fields to the migration:
Why are we using bigInteger
for restaurant_id
? Primary keys are created with id()
, which creates a big integer column that automatically increments. To match data types, we create a column with the same big integer data type.
And in the model file, mark these fields as fillable:
Go ahead and migrate the database again:
Our models will automatically detect the columns on them, but to use relationships we need to declare them. Add the following to Restaurant.php
:
This allows you to get to a restaurant’s dishes. Let’s make a way to get back from the dish to a restaurant too. Add the following to Dish.php
:
Now that our models are set up, we can create some records. You could do it by hand, but Laravel has the concept of seeder files, which allow you to “seed” your database with sample data. Let’s use them to set up some data.
Generate a seeder file:
This will create a file RestaurantSeeder.php
in the database/seeders/
folder. Add the following to it:
Note that we can just pass the attributes to the ::create()
method in an array. Notice, too, that we can access the dishes()
relationship for a given restaurant, then createMany()
records on that relationship—that way Laravel knows what foreign key value to provide for the restaurant
relationship.
Next, call that seeder file from the main DatabaseSeeder.php
:
Run the seed command to seed the database:
Setting Up the Web Service
Now that we’ve got our data all set, let’s set up Laravel JSON API (LJA) so we can access it via a web service.
Add LJA and its associated testing library to your project’s dependencies using Composer:
Next, we need to make a few configuration tweaks. By default, Laravel adds an /api/
prefix to API routes, but LJA also has functionality to add prefixes like /api/v1/
to your API routes. To prevent these from conflicting, let’s remove Laravel’s default /api/
prefix set up in app/Providers/RouteServiceProvider.php
:
The LJA guides also describe setting up JSON-specific exception handling, but leaving this off for now can help us easily see any stack traces we get as we’re getting the API set up.
LJA can host multiple APIs in the same Laravel application, so first we need to generate the default API:
This creates a file config/json-api-default.php
. We just have to configure one thing in there: which models are available as resources in the API. Find the 'resources'
key and make the following change:
For each of these resources, we need to create a “schema”, a class that instructs LJA which attributes and relationships to expose. Generate a schema for each of our two models:
These commands together create a directory app/JsonApi/
with a folder under them for each of our two resources. Each folder has a Schema.php
file. Open app/JsonApi/Restaurants/Schema.php
and find the function getAttributes()
. Add our string attributes to it:
Note that created-at
and updated-at
are exposed automatically.
We also want to expose the dishes
relationship on a restaurant. Add the following function to the Schema
class:
Now make analogous changes to the Dishes/Schema.php
file:
We need to generate one more type of class for each of our models: an adapter. LJA uses the adapter to find how to query the relationships for each model type. Generate an adapter for each model:
Under our app/JsonApi
folders for each model, this creates an Adapter.php
class. First open Restaurants/Adapter.php
.
In the __construct()
function, we need to update the reference to the model to use the AppModels
namespace that newer versions of Laravel use:
We also need to add a dishes()
function:
This indicates to LJA that dishes
is a has-many relationship.
Make analogous changes to Dishes/Adapter.php
The last piece of the puzzle is hooking up the routes. Open routes/api.php
and you’ll see the following:
Api Key Steam
This is where all the routes for your app are configured. LJA provides a function that will set up routes the way LJA needs. Add the following at the end of the file:
Note that we specify both the main resources and the relationships available on them. This will set up all necessary routes. For example, for restaurants, the following main routes are created:
- GET /restaurants — lists all the restaurants
- POST /restaurants — creates a new restaurant
- GET /restaurants/:id — gets one restaurant
- PATCH /restaurants/:id — updates a restaurant
- DELETE /restaurants/:id — deletes a restaurant
That’s a lot we’ve gotten without having to write almost any code!
Trying It Out
Now let’s give it a try.
Visit http://opinion-ate.test/api/v1/restaurants/1
in your browser. You should see something like the following:
If you’re using Firefox you should see the JSON data nicely formatted. If your browser doesn’t automatically format JSON, you may be able to find a browser extension to do so. For example, for Chrome you can use JSONView.
This is a JSON:API response for a single record. Let’s talk about what’s going on here:
- The top-level
data
property contains the main data for the response. In this case it’s one record; it can also be an array. - Even if you can infer the type of the record from context, JSON:API records always have a
type
field recording which type they are. In some contexts, records of different types will be intermixed in an array, so this keeps them distinct. - The record contains an
id
property giving the record’s publicly-exposed ID, which by default is the database integer ID. But JSON:API IDs are always exposed as strings, to allow for the possibility of slugs or UUIDs. attributes
is an object containing all the attributes we exposed. They are nested instead of directly on the record to avoid colliding with other standard JSON:API properties liketype
.relationships
provides data on the relationships for this record. In this case, the record has adishes
relationship. Twolinks
are provided to get data related to that relationship:- The
self
link conceptually provides the relationships themselves, which is to say just the IDs of the related records - The
related
link provides the full related records.
- The
Try visiting the related
link, http://opinion-ate.test/api/v1/restaurants/1/dishes
, in the browser. You’ll see the following:
Note that this time the data
is an array of two records. Each of them also has their own relationships
getting back to the restaurants
associated with the record. These relationships are where LJA really shines. Instead of having to manually build routes, controllers, and queries for all of these relationships, LJA exposes them for you. And because it uses the standard JSON:API format, there are prebuilt client tools that can save you the same kind of code on the frontend!
What Is My Api Key
Next, let’s take a look at the restaurants list view. Visit http://opinion-ate.test/api/v1/restaurants
and you’ll see all the records returned.
Next, let’s try creating a record. We won’t be able to do this in the browser; we’ll need a more sophisticated web service client to do so. One good option is Postman—download it and start it up.
You can use Postman for GET requests as well: set up a GET request to http://opinion-ate.test/api/v1/restaurants
and see how it displays the same data as the browser.
Next, let’s create a POST request to the same URL, http://opinion-ate.test/api/v1/restaurants
. Go to the Headers tab and enter key “Content-Type” and value “application/vnd.api+json”—this is the content type JSON:API requires.
Next, switch to the Body tab. Click the “none” dropdown and change it to “raw”. Another “Text” dropdown will appear; change it to “JSON”. Enter the following:
Notice that we don’t have to provide an id
because we’re relying on the server to generate it. And we don’t have to provide the relationships
or links
, just the attributes
we want to set on the new record.
Now that our request is set up, click Send and you should get a “201 Created” response, with the following body:
Our new record is created and the data is returned to us!
Generate Api Key Php Laravel Tutorial
If you’d like to try out updating and deleting records:
Generate Api Key Php Laravel Download
- Make a
PATCH
request tohttp://opinion-ate.test/api/v1/restaurants/3
, passing in updatedattributes
. - Make a
DELETE
request tohttp://opinion-ate.test/api/v1/restaurants/3
with no body to delete the record.
There’s More
Generate Api Key In Laravel
We’ve seen a ton of help Laravel JSON API has provided us: the ability to create, read, update, and delete records, including record relationships. But it offers a lot more too! It allows you to configure Laravel validators to run, allows you to request only a subset of the fields you need, allows you to include related records in the response, as well as sorting, filtering, and pagination. To learn more, check out the Laravel JSON API Docs.
Generate Api Key Php Laravel Download
Now that you have a JSON:API backend, you should try connecting to it from the frontend. Choose a tutorial from the How to JSON:API home page!