API in Laravel
API in Laravel

API in Laravel

  1. make a controller
  1. Import the controller inside api.php
notion image
to access the url you should add api/ before writing the actual route
notion image
Β 
Β 

With param

notion image
Β 
Β 

Post API

notion image
Β 

Search API

notion image
for this functionality you have to add some string in where clause of the DB class in model
notion image
add β€œlike” attribute and β€œ%” before and after the attribute .
Β 
Β 

API validations

suppose you want to validate the password length or some other property so you have to import the Validate class inside controller
notion image
You have to define a array of rules such as what fields are required and pass all the request parameters to the Validator class
notion image
After validating the request params you can show the results
notion image
Β 

API with resources

Β 
Β 
Β 

API authentications

πŸŽ™οΈ
Sanctum
first you have to install sanctum
composer require laravel/sanctum
Now you have to publish the sanctum β†’ This will create some of the neccessary file to migrate
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
As we discussed , we have to now migrate the database
php artisan migrate
Now we have to add a line inside kernel.php
notion image
Now we have to add a middleware inside global middleware array
notion image
πŸ”₯
You will have a defult model User if not then make a model with command line and then import the HasApiTokens class from laravel/sanctum
notion image
Now to add some dummy data inside users table , we will use seeders
php artisan make:seeder UserTableSeeder
notion image
Now we have to seed to save the data inside database
php artisan db:seed --class=UserTableSeeder
Make A Controller
now we will create a controller to check all the things working or not
php artisan make:controller UserController
now make a function which validates the name and email of the user and then create a API token for the respective user
class UserController extends Controller { function index(Request $request) $usert= User::where( 'email' ,$request->email)->first( ) ; // print_r($data); if (!$user || !Hash:: check($request->password, $user->password)) { return response([ ' message '=> ['These credentials do not match our records. 'J J, 404); } $token = $user->createToken( 'my-app-token' )->p1ainTextToken; $response =[ 'user'=>$user, 'token' => $token ]; return response($response,201); } }
Now make a view to connect with controller
notion image
notion image
To Check the functionality you can go to the user route in api and send a get request
notion image
You have to send Headers with key = Authorization and value = Bearer token_value
To Apply the token to all api routed other than login , you can set it as
notion image
Β