Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Build Secure PHP REST API in Laravel 9 with Sanctum Auth

Laravel Sanctum authentication tutorial; In this tutorial, we will share how to create or build a secure PHP RESTful API in the Laravel application with the help of the Laravel sanctum package.

Likewise, we will explain to you step by step how to test the Laravel Sanctum authentication REST API using the Postman testing tool.

Laravel Sanctum offers an immaculate, secure, blazingly fast, a lightweight authentication system for single-page applications (SPA), mobile applications, and simple, token-based APIs.

Sanctum is a profound package that allows every user to generate multiple API tokens for their account independently. These tokens grant various roles and scopes that designate which actions the tokens are entitled to perform.

Follow the below few steps to create a restful API example in the laravel 9 app.

Step 1: Install Laravel9

You have to open the terminal and add the following command to create a Laravel project. But, ensure you have composer installed on your system.

composer create-project laravel/laravel example-app
Step 2: Use Sanctum

In this step we need to install sanctum via the Composer package manager, so one your terminal and fire the below command:

composer require laravel/sanctum

After successfully installing the package, we need to publish the configuration file with the following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

we require to get default migration to create new sanctum tables in our database. so let’s run the bellow command.

php artisan migrate

Next, we need to add middleware for sanctum api, so let’s add as like below:

app/Http/Kernel.php
....
  
'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
  
....

Step 3: Sanctum Configuration

In this step, we have to configure three place models, service providers, and auth config files. So you have to just follow the change on that file.

In the model, we added HasApiTokens class of Sanctum,

In auth.php, we added api auth configuration.

app/Models/User.php
 'datetime',
    ];
}

Step 4: Add Product Table and Model

Use the PHP artisan command to create a new blog migration table, type the command on the terminal, and execute it to generate a new migration file.

php artisan make:migration create_products_table

After this command, you will find one file in the following path database/migrations and you have to put the below code in your migration file for creating a products table.

id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};

Run recommended command to run database migration:

php artisan migrate

After creating the “products” table you should create a Product model for products, so first create a file in this path app/Models/Product.php and put the bellow content in the item.php file:

app/Models/Product.php

Step 5: Create API Routes

In this step, we will create API routes for login, register, and product rest api. So, let’s add a new route to that file.

routes/api.php

group(function(){
    Route::post('register', 'register');
    Route::post('login', 'login');
});
        
Route::middleware('auth:sanctum')->group( function () {
    Route::resource('products', ProductController::class);
});

Step 6: Create Controller Files

Next, we need to create three controllers to handle the auth process; first, create an API directory into the Controllers folder; after that, create three files simultaneously within the folder naming them AuthController, BaseController, and BlogController.

These files will individually handle login, signup, and blog crud operations.

Subsequently, add the code in the app/Http/Controllers/API/BaseController.php file:

 true,
            'data'    => $result,
            'message' => $message,
        ];

        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];

        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}
app/Http/Controllers/API/RegisterController.php
all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->plainTextToken;
        $success['name'] =  $user->name;
   
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}
app/Http/Controllers/API/ProductController.php
sendResponse(ProductResource::collection($products), 'Products retrieved successfully.');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $product = Product::create($input);
   
        return $this->sendResponse(new ProductResource($product), 'Product created successfully.');
    } 
   
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = Product::find($id);
  
        if (is_null($product)) {
            return $this->sendError('Product not found.');
        }
   
        return $this->sendResponse(new ProductResource($product), 'Product retrieved successfully.');
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $product->name = $input['name'];
        $product->detail = $input['detail'];
        $product->save();
   
        return $this->sendResponse(new ProductResource($product), 'Product updated successfully.');
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();
   
        return $this->sendResponse([], 'Product deleted successfully.');
    }
}

Step 7: Create Eloquent API Resources

This is a very important step in creating rest api in laravel 9. you can use eloquent api resources with api. it will help you to make some response layouts of your model object. we used in the ProductController file. now we have to create it using the following command


php artisan make:resource ProductResource

Now there created a new file with a new folder on the following path:

app/Http/Resources/ProductResource.php
 $this->id,
            'name' => $this->name,
            'detail' => $this->detail,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->format('d/m/Y'),
        ];
    }
}

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your postman and check the following apis.
make sure in details api we will use the following headers as listed below:

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
]

Here is Routes URL with Verb:

1) Register API: Verb: GET, URL:http://localhost:8000/api/register
2) Login API: Verb: GET, URL:http://localhost:8000/api/login
3) Product List API: Verb: GET, URL:http://localhost:8000/api/products
4) Product Create API: Verb: POST, URL:http://localhost:8000/api/products
5) Product Show API: Verb: GET, URL:http://localhost:8000/api/products/{id}
6) Product Update API: Verb: PUT, URL:http://localhost:8000/api/products/{id}
7) Product Delete API: Verb: DELETE, URL:http://localhost:8000/api/products/{id}

The post Build Secure PHP REST API in Laravel 9 with Sanctum Auth appeared first on Magespider Solutions.



This post first appeared on Software & Mobile App Development, please read the originial post: here

Share the post

Build Secure PHP REST API in Laravel 9 with Sanctum Auth

×

Subscribe to Software & Mobile App Development

Get updates delivered right to your inbox!

Thank you for your subscription

×