Laravel Eloquent is a simple approach to have interaction along side your database. It’s an object-relational mapper (ORM) that simplifies the complexities of databases via providing a model to engage with tables.
As such, Laravel Eloquent has superb tools for rising and checking out APIs to reinforce your development. In this hands-on article, you’ll see how easy it’s to create and test APIs the use of Laravel.
In this demonstration, you’ll get began via creating a model that you just’ll have the ability to use to build the API and database table. Then, you’ll see learn how to add a controller as a business commonplace sense layer and a path to complete the API. You’ll then learn how to perform checking out APIs the use of Postman previous to in any case focusing on authentication and error coping with.
Must haves
To get started, proper right here’s what you’ll need:
- Laravel model 8 or 9
- Composer
- Postman
- XAMPP
- Basic knowledge of APIs and PHP
API Basics
Get began via rising a brand spanking new Laravel project the use of composer
:
composer create-project laravel/laravel laravel-api-create-test
To start out out the server, execute the following command, which runs the application server on port 8000:
cd laravel-api-create-test
php artisan serve
You’ll have to see the following computer screen:
Then, create a model with a -m
flag for the migration the use of the code underneath:
php artisan make:model Product -m
Now reinforce the migration record to include the specified field. Add title and description fields for the product model and the ones two table fields throughout the database/migrations/{date_stamp}_create_products_table.php record.
$table->string('title');
$table->longText('description');
The next step is to make the ones fields fillable. Within app/Models/Product.php, make title
and description
fillable fields.
secure $fillable = ['title', 'description'];
How To Create a Controller
Now, create a controller record for the product via executing the following command. This may occasionally every now and then create the app/Http/Controllers/Api/ProductController.php record.
php artisan make:controller ApiProductController --model=Product
Now, add the commonsense for rising and retrieving the products. Throughout the index
way, add the following code to retrieve all of the products:
$products = Product::all();
return response()->json([
'status' => true,
'products' => $products
]);
After that, you’ll have to add a StoreProductRequest
class for storing the new products throughout the database. Add the following class at the top of the an identical record.
public function store(StoreProductRequest $request)
{
$product = Product::create($request->all());
return response()->json([
'status' => true,
'message' => "Product Created successfully!",
'product' => $product
], 200);
}
Now, you’ll create the request, which you’ll have the ability to do via executing the following command:
php artisan make:request StoreProductRequest
If you want to add validations, you’ll have the ability to use the app/Http/Requests/StoreProductRequest.php record. For this demonstration, there aren’t any validations.
How To Create a Route
The entire step previous to checking out the API is together with a path. To do so, add the following code throughout the routes/api.php record. Add the use
statement at first of the record and the Route
statement throughout the body:
use AppHttpControllersApiProductController;
Route::apiResource('products', ProductController::class);
Quicker than you get began checking out the API, ensure that the products table is in your database. If it doesn’t exist, create one the use of a control panel like XAMPP. Then again, you’ll have the ability to execute the following command to migrate the database:
php artisan migrate
How To Take a look at an API
Quicker than checking out the API, ensure that the authorize
way throughout the app/Http/Requests/StoreProductRequest.php is able to return true
.
Now, you’ll have the ability to create a brand spanking new product the use of Postman. Get began via hitting a POST
request to this URL: http://127.0.0.1:8000/api/merchandise/. Because of it’s a POST
request for rising a brand spanking new product, you’ll have to move a JSON object with a reputation and description.
{
"title":"Apple",
"description":"Easiest Apples of the field"
}
After clicking the Send button, you’ll have to see the following:
Now, fetch the created products the use of the GET
request. The URL is the same. The results will seem to be the following:
How To Authenticate an API Using Sanctum
Authentication is the most important when securing an API. Laravel makes it easy via providing the potential of the Sanctum token, which you’ll have the ability to use as middleware. It secures the API the use of tokens generated when the individual logs in the use of the correct credentials. Remember that shoppers can’t get right to use the secured API and no longer the usage of a token.
The first step to together with authentication is so that you can upload a Sanctum package the use of the code underneath:
composer require laravel/sanctum
Then, publish the Sanctum configuration record:
php artisan dealer:publish --provider="LaravelSanctumSanctumServiceProvider"
After that, add Sanctum’s token as middleware. Throughout the app/Http/Kernel.php record, use the following class and trade middlewareGroups
with the following code throughout the secure middleware groups’ API.
use LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful;
secure $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
// IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
];
The next step is to create a UserController
and add the code to get the token to authenticate.
php artisan make:controller UserController
After rising the UserController
, navigate to the app/Http/Controllers/UserController.php record and trade the prevailing code with the following code:
e-mail)->first();
// print_r($knowledge);
if (!$particular person || !Hash::check out($request->password, $user->password)) {
return response([
'message' => ['These credentials do not match our records.']
], 404);
}
$token = $user->createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
}
Quicker than you’ll have the ability to test the authentication, create an individual the usage of seeders. The following command creates a UsersTableSeeder record.
php artisan make:seeder UsersTableSeeder
Throughout the database/seeders/UsersTableSeeder.php record, trade the prevailing code with the following code to seed the individual:
insert([
'name' => 'John Doe',
'email' => 'john@doe.com',
'password' => Hash::make('password')
]);
}
}
Now run the seeder the use of this command:
php artisan db:seed --class=UsersTableSeeder
The rest step left throughout the authentication drift is to use the created middleware to protect the path. Navigate to the routes/api.php record and add the products path throughout the middleware.
use AppHttpControllersUserController;
Route::workforce(['middleware' => 'auth:sanctum'], function () {
Route::apiResource('products', ProductController::class);
});
Route::submit("login",[UserController::class,'index']);
After together with a trail to the middleware, you’ll get an inside server error if you happen to try to fetch the products.
On the other hand when you log in, get a token, and use it throughout the header, it’s going to authenticate you and get began operating. You’ll send a POST request to http://127.0.0.1:8000/api/login with the following body:
{
"e-mail":"john@doe.com",
"password":"password"
}
Use the token received as a Bearer token and add it for the reason that Authorization header.
How To Care for API Errors
Each time you send a request to the server, it responds. With the response, it moreover sends a standing code consistent with the nature of the response. For example, a 200 status code implies that the request has succeeded, and a 404 signifies that the server can’t to search out the requested helpful useful resource.
On the other hand, a status code isn’t enough. A human-readable error message is wanted. Laravel comes with many ways to deal with errors. You’ll use a try-catch block, the fallback way, or send a custom designed response. The following code you added to the UserController
demonstrates this.
if (!$particular person || !Hash::check out($request->password, $user->password)) {
return response([
'message' => ['These credentials do not match our records.']
], 404);
}
Summary
Laravel’s Eloquent Type makes it simple to create, validate, and test APIs. Its object-relational mapping provides a easy technique to interacting with the database.
Additionally, appearing as middleware, Laravel’s Sanctum token let you to secure your APIs in brief.
And if you want to have further optimization, Kinsta’s Database Web hosting answer simplifies setting up and managing databases for your entire web projects.
The submit Laravel API: Create and Check an API in Laravel gave the impression first on Kinsta®.
Contents
- 1 Must haves
- 2 API Basics
- 3 How To Create a Controller
- 4 How To Create a Route
- 5 How To Take a look at an API
- 6 How To Authenticate an API Using Sanctum
- 7 How To Care for API Errors
- 8 Summary
- 9 WordPress vs HubSpot CMS
- 10 Imposing AI in Your Advertising and marketing Tech Stack — Pointers and Tips You Want to Know
- 11 7 WordPress Building Developments to Apply Proper Now
0 Comments