- make a controller
- Import the controller inside api.php
to access the url you should add api/ before writing the actual route
Β
Β
With param
Β
Β
Post API
Β
Search API
for this functionality you have to add some string in where clause of the DB class in model
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
You have to define a array of rules such as what fields are required and pass all the request parameters to the Validator class
After validating the request params you can show the results
Β
API with resources
Β
Β
Β
API authentications
Sanctumfirst 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
Now we have to add a middleware inside global middleware array
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
Now to add some dummy data inside users table , we will use seeders
php artisan make:seeder UserTableSeeder
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
To Check the functionality you can go to the user route in api and send a get request
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
Β