8.X Laravel - How to create REST API with Laravel

Published August 18, 2021

In this Laravel Tutorial examples we will cover how to create Rest API with Laravel 8. Before that we need to know

What is REST API?

API stands for Application Program Interface. There are multiple types of APIs however in this PHP Laravel 8.x tutorial article we will learn how to make REST API in Laravel.

Note: REST stands for Representational State Transfer. REST API interacts with restful web services.

 

Features of REST API in Laravel

APIs are a great way to develop both web applications as well as cross platform applications. You don’t need to develop different backend for different platforms. Once you have APIs ready in Laravel, you can consume them in Web, Android, iOS or any other platform. 

 

How to write your first Laravel RESTFUL API with Passport Authentication Package

 

Download Source code

 

Follow the steps below to start creating APIs in Laravel from scratch.

 

Requirements

  1. Code Editor – Visual Studio Code (recommended)

  2. Composer – To install composer type following command in terminal.

Composer install –ignore-platform-reqs

 

Start creating Laravel 8.x API 

  1. Open terminal and type the following command to create a new laravel 8.x project.

composer create-project --prefer-dist laravel/laravel laravel-REST-API

 

  1. You will have a new folder at the  directory where you created the project. Type following command to jump into the project folder.

Cd project_folder_path

 

  1. Configure database connection in Laravel 8.x. The connection variables are placed in .env file present in the root directory of the project.

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=database_name

DB_USERNAME=root

DB_PASSWORD=

 

Note: Before moving to the next step, you must Know about the Laravel Passport package. This package provides Authentication using token sessions stored in the database. So, you don’t need to authenticate the user manually.

  1. Run the following command to install the Laravel Passport package.

 

Composer require laravel/passport

This command creates some default migration files. So, run the migration command and then another command to generate the access token.

Php artisan migrate

 

Php artisan passport:instal

 

  1. Make configurations in followimg files for passport.

    • Config/app.php – Add following class in providers array

'providers' => [

        ...

        Laravel\Passport\PassportServiceProvider::class,

    ],

 

  • config/auth.php – Change driver to passport in api array

'guards' => [

    'web' => [

        'driver' => 'session',

        'provider' => 'users',

    ],


    'api' => [

        'driver' => 'passport',

        'provider' => 'users',

    ],

],

 

  • app/Models/User.php – use HasApiTokens

<?php


namespace App\Models;


use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;


use Laravel\Passport\HasApiTokens;


class User extends Authenticatable

{

    use HasFactory, Notifiable, HasApiTokens;


    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'name',

        'email',

        'password',

    ];


    /**

     * The attributes that should be hidden for arrays.

     *

     * @var array

     */

    protected $hidden = [

        'password',

        'remember_token',

    ];


    /**

     * The attributes that should be cast to native types.

     *

     * @var array

     */

    protected $casts = [

        'email_verified_at' => 'datetime',

    ];

}

 

  • app/Providers/AuthServiceProvider.php – Add passport static method in boot method.

<?php


namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

use Illuminate\Support\Facades\Gate;


use Laravel\Passport\Passport;



class AuthServiceProvider extends ServiceProvider

{

    /**

     * The policy mappings for the application.

     *

     * @var array

     */

    protected $policies = [

        'App\Models\Model' => 'App\Policies\ModelPolicy',

    ];



    /**

     * Register any authentication / authorization services.

     *

     * @return void

     */

    public function boot()

    {

        $this->registerPolicies();

        Passport::routes();

    }

}

 

Now, you are good to go for creating a model, migration and controller for your API.

  1. Run the following command in the terminal to create a model and migration for your database table.

Php artisan make:model Contacts -m

 

Migration and model can be created one by one but using -m  will create migration file and model file for it automatically. It follows the standard naming conventions to name the model and migration file.

Add the required columns in the migration and model file and also include HasTokenApi in the model, just like you have done for the passport model above. 

  • Run command php artisan migrate

 

  1. Run the following command to create a controller for business logic.

Php artisan make:controller Contacts

 

  1. Before writing your logic in Contacts controller, first add following code in the AuthController.php file

< ?php

namespace
App\Http\Controllers;

use
Illuminate\Http\Request;

use
App\Models\User;


class AuthController extends Controller


{

/ **

*Signin

 * /

 public
function
signin(Request $request)

{

$data = [

    'email' = > $request->email,

                          'password' = > $request->password

];



if (auth()->attempt($data)) {

$token = auth()->user()->createToken('LaravelPassportRestApiExample')->accessToken;

return response()->json(['token' = > $token], 200);

} else {

return response()->json(['error' = > 'Unauthorised'], 401);

}

}

/ **

*Signup

 * /

 public
function
signup(Request $request)

{

$this->validate($request, [

    'name' = > 'required|min:2',

               'email' = > 'required|email',

                           'password' = > 'required|min:4',

]);



$user = User::create([

    'name' = > $request->name,

                         'email' = > $request->email,

                                               'password' = > bcrypt($request->password)

]);



$token = $user->createToken('LaravelPassportRestApiExampl')->accessToken;

return response()->json(['token' = > $token], 200);

}

}

 

  1. In Contacts.php start writing your function. Sample is provided below.

< ?php

namespace
App\Http\Controllers;

use
Illuminate\Http\Request;

use
App\Models\Contact;


class Contact extends Controller


{

    public
function
index()

{

$contact = auth()->user()->contact;

return response()->json([

    'success' = > true,

                  'data' = > $contact

]);

}



public
function
show($id)

{

$contact = auth()->user()->contact()->find($id);



if (!$contact) {

return response()->json([

    'success' = > false,

                  'message' = > 'Blog is not available! '

], 400);

}



return response()->json([

    'success' = > true,

                  'data' = > $contact->toArray()

], 400);

}


public
function
add(Request $request)

{

$input = $request->all();



$validator = Validator::make($input, [

    'name' = > 'required',

               'number' = > 'required'

]);



if ($validator->fails()){

return $this->sendError('Validation Error.', $validator->errors());

}



$contact = Contact::create($input);



return response()->json([

    'success' = > true,

                  'data' = > $contact->toArray()

], 200);

}


public
function
update(Request $request)

{

$input = $request->all();



$validator = Validator::make($input, [

    'name' = > 'required',

               'number' = > 'required'

]);



if ($validator->fails()){

return $this->sendError('Validation Error.', $validator->errors());

}


$product = Product::find($request->product_id);

$product->name = $input['name'];

$product->number = $input['number'];

$product->save();

return response()->json([

    'success' = > true,

                  'data' = > $contact->toArray()

], 200);}


 

 

  1. Now, the last step is to register REST API routes in routes/api.php file. 

Route::post('showContact', [Contact::class, 'show']);

Route::post('addContact', [Contact::class, 'add']);

Route::post('updateContact', [Contact::class, 'update']);

 

Done! You have successfully created your first REST API in Laravel 8.x. To run the project run following command

 

Php artisan serve

 

Your project is now running on address localhost:80 or http://127.0.0.1:80

Tip 1: To test the APIs, use the Postman API testing tool. You can download it from here.

Tip 2: Keep the name of Model and controller file singular. Whereas, migration and database table name plural.

 

Conculsion: PHP Rest API with Laravel 8.x version. Create Passport Authentication Routes, create controllers, create api controller with Laravel

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

3194 Views