How to build RESTful API using Laravel 8.x and JWT Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello guys welcome to my youtube channel texted blog this is surujit and in this video tutorial we are going to build a restful api using laravel and time on jwt authentication so it will ask me what is jwt jwt is json web token when a user logs into the server the server will generate a token for the user if the user is authenticated then the authenticated user can view create modify and delete some restricted data at first we need to install level so let me open the documentation so you can see the installation so here you can see the requirement of this uh server that is php which is need to be 7.3 or greater vcm php extension c type php extension file info this um library need to be installed for php and the and then the installing laravel so via laravel installer so you need to have a composer so before downloading this laravel installer you should have composer okay so using this uh command you can install this laravel installer then you need to configure your a profile so you know if you are in a windows platform you need to create the environmental variable like this one and if you are in a mac os you need to export your profile in your bashrc or jshrc to indicate that this is the point where your laravel installer has been installed okay and for the linux distribution you can use this a path and then you can use this laravel new blog this blog is a project name and the level command will create a new laravel framework in your project directory so let me open the terminal and cd into the desktop and in our desktop we are going to create laravel new laravel api so our laravel framework has been installed so we need to cd into our project directory so laravel api and if we need to see the project structure you can see we have app bootstrap composer.log database public resources server.php webpack mix.js artisan package.json readme.md routes storage vendor okay and here if you visit this page gwt hyphen auth dot read the docs dot io en docs quick start you will see how to install this jwt composer require time on jwt auth and here you can see some configuration for this jwt so for this i'm going to open my terminal and going to install using composer composer require then time on jwt auth dev develop prefer source and hit enter so this gwt package has been installed now we need to publish the this jwt config so so what we need to do is we need to use this command php artisan vendor publish right here you can see from the nine option time on jwtr providers laravel service provider so we need to uh select this ninth option and hit enter and it will copy the file from config config.php to config jwg.php so i'm just going to clear this and now we need to generate a secret code so it will uh generate this secret code in our in eng file so php artisan jwt colon secret and hit enter and if you uh open this project in your text editor i'm just going to use a visual uh vim you can use visual studio code or sublime text and then you can open this env file and here you can see jwt secret okay now as we are going to use our database so we need to uh make some configuration right here we are going to give the database name as laravel api the username is root and the password is going to be password okay and we are going to save this file okay city right now we have this and we need to open our config folder then auth.php and here we are going to use the default guard that is api and then in our api driver we are going to use the jwt and list is as it is okay then we are going to open the routes folder and inside the routes folder we're going to go to the api.php file so we need to remove this and after that we need to use route group and then an array a closure and in our array we can use the middleware which is our api middleware then we are going to use namespace and the namespace is going to be app http controllers and we are going to use a prefix the previous should be auth and in our function you can use router and then in our function block we can use route then post here we are going to use five endpoints so here first thing is login then auth controller then auth controller we are going to use login method and paste five times and then register here we are going to use log out which is a post endpoint then profile if user want to see their profile they can use this profile and the method of this http method is going to be get and profile and the last thing we are going to use refresh we can refresh our token in a certain time using this refresh endpoint which is going to be a post http method and we have this so far and we can also use another thing that you can copy this and paste here and we are going to use api middleware and we don't have any prefix so we can only just use route resource and then a to do's endpoint and then we are going to use uh to do controller so as it will be resourceful controller laravel will identify everything that is um stored index everything okay so we will create to-do controller later and now we need to open our user.php model and here we need to implement an interface so the interface is jwt subject and it will auto import this gwd subject and here you can see we need to use a two method get jwt identifier and get gwt custom themes and in our here you can see public function get jwp identifier returned this get keys and after that we need to use another method that is get jwt custom times return an empty error so this is our user model and we can save this file now we need to create an auth controller so for this we need to go to our terminal here we just going to make php artisan make controller auth controller and hit enter and if we go to our http controllers folder you can see authcontroller.php file has been created so here we are going to use public function a construct method and here we are going to use a middleware that is auth api and then accept login and then register so this accept means we are not going to use this api on our login and register okay now after that protected protected function card and we are going to return auth facade so auth facade and then guard and then here we are going to use public function login and then request request another thing that is public function register then request request and after that public function log out public function profile and then public function refresh so in our login method you need to make a validator variable and we need to import this validator facade so illuminate support facades and then we need to use a make method and you can see here we need to pass data which is a an array and the rules rules also be an array so that the data should be request all and then an array for rules so first name first thing is an email email is required and it should be email and then password password is required and it should be string and the minimum is minimum character of this password should be six okay now if validator fails then we are going to return response json that should be validated errors and we are going to use four zero zero bed which is bad request or we can use uh yes bad request so if you want to know what is 400 this is going to be a bad request so and then we are going to make another variable that is going to be token validity so we are going to use a one one day validity for this token so we need to multiply this 24 with 60 and it will convert to into a minute now we need to use this guard and then factory and set ttl and we need to pass this token variety and then after that if not dollar token equal to this guard attempt validator validated then if the user trying to enter wrong using a wrong email or password we need to show return response with json and then here we are going to use the 401 status code and then we are going to show error and authorized then if everything goes well we're going to use return this respond with token and we're going to pass this token make another protected function that is protected function respond with token return response json so here we are going to pass a token which is a token and then token type is bearer and then token validity that is uh we can use this card factory get ttl into 60 it will show us in a second so save this file now after login method we can create our we can build our register method use validator then valley updater make request all here we just need to use a name which is required this should be string and between to 200 then email this should be required this should be email and then it should be unique so that we are going to only store unique email address okay so unique from the users table and the password required confirmed minimum password character should be 6 now if validator fails then return response json we are going to use for four double two and then um uh we're going to pass validator errors this one and if everything goes well we just need to use user variable then user create then array merge request and not this validator validated and then an array which have a password and then we're going to use bigcrypt and then we are going to use bigcrypt function and here we are going to pass request password and then return response json then message user created successfully and then user user so for the log out you need to use this card then log out return response json message user logged out accept this one and for the profile we can return response json this card user and for the refresh we need to return this respond with token and we need to use this card refresh so we successfully created our earth controller now we need to create another model that is to do model so we are going to create a to do model a magnesium file as well as a resourceful controller as we talked earlier now we need to use this command that is php artisan make model that is to do with mcr option and hit enter so our magnesium file has been created and in our database directory in our migration you can see we have this crea to do stable with a timestamp now here we are going to create table uh table that should be string title then table text that should be body table boolean that should be completed and then table unsigned big integer should be created at uh sorry created by and then we are going to create a foreign key table foreign and here we just need to use created by then references id on a table the table name should be users and on delete cascade so after that we need to open our user model because we have we need to use the relation so public function to do's written this has many we are going to use to do model so if we reload this this to do class and then created by and id so you can see to do class is the related model and this one is a foreign key and this one is a local key local key means the primary key of this user model okay now we need to open the refresh it you can see the to-do controller right here and we can see that we have this index create store show edit update and destroy so this is a resourceful controller and we just need to remove this create then store we need we need show we need edit we don't need edit so we can delete it and now we need to create a protected property protected user and then public function construct and then we are going to use this middleware that should be auth api and then in our index function and last we are going to use protected function guard return auth so earth we need to import this hazard and then auth card and after that right here after this middleware we are going to use user not user this user this guard user okay now in our index we can say to those this user then to do's get now we need to get a title body then completed then created by and then we need to show it as a response so return response json here then you got booked at it and after that we need to go to our store method so we need to use validator illuminate support for search make the request all and then the title required string body [Music] boolean you need the only this uh three fields and after that if validator fails return response this one with a bad request and that should be status false and then errors this not this validator errors and then to do new so let's see what is today so to do new to do and then to do uh title uh request title due to body request body to do completed request completed and then if this user to do's return response just on status true and then to do to do let's see why it's showing undefined type app models to do no problem we will see if any error arises when when we use our postman right now we are not going to use this show a method so we can remove this or we can keep this so we can use return to do like this one and then public function update we can copy validator then you can copy this and if this error okay now if anything goes wrong after if statement else return response json status equal to false message oops that to do could not be saved so we can copy this and paste it after the ips air statement like this and here we replace the shape to update it and for the destroy you can use if dollar to do delete then you can use this response status true to do to do and then this else block copy message false status false and then could not be deleted this is so far now we need to open our postman which is a restful api client so you can so you can search in from google for postman api download download postman and you can use the postman app download the app for linux here you can see so i already installed it and i'm going to open this postman and after that i just need to go to the command line and use php artisan php artisan serve so it will start a development server in this 8 000 port so you can copy this and in our postman we can close this and here we just going to open this tab and here we can paste it and we can use post method and then if we send this so before doing that we need to make it as api auth login send and you can see email the email field is required password the password field is required so we can make it as body form data or you can use error data also so email and we are going to use a wrong email and password is password and then press send okay we need to use a header so header accept accept application json okay unknown database laravel api so we need to open our terminal here we need to do is php artisan migrate okay we need we are in a public folder so we need to go to the widget folder so php artisan migrate unknown database level api so uh again we need to go to the localhost uh we are going to use the psp my main gui and here we need to close level api then utf-8 general ci create okay this database has been created so we can go to our you can make this again so php artisan migrate then we need to see that we have this users table which have id name email email verified ad password remember token created ad and updated at columns and another thing we have that is to do's the structure you can see we have id title body completed which is a tiny int which is a boolean and we need to make it as default uh default to zero because when an user creates a to do that should be by default zero which means completed is false so we can go to our migration file can open this file and completed we are going to make it the default value as false so false means zero and here we can make the fresh migration and now if i now go to structure you will see the default is 0 right now and the created by you can see this is this has a index which is to do stated by foreign for the foreign key and if you want to see let's see relation view you will see the to-do's created by foreign created by this column the database is laravel api table is user stable and the related uh column is id okay now we need to go to our uh project folder so here you can see we have our database directory and inside the database directory we have a factory so we can use this factory user factory and we can remove this and use bigcrypt and inside it we are going to use default as password you can use one two three four or anything else i'm just going to use password and save it and for the uh to do for the to do stable we are going to use php artisan php artisan make factory to do factory now reload here you can see we have this return array so here we are going to use title as this faker sentence then body this faker paragraph then completed we are going to use a random from 0 to 1 and then created by with random of 1 to 10 so this one and after that we need to use a tinker shell so for this php artisan uh tinker tinker is a php shell so you can see psy shell version is 10.4 0.10.4 and it is using 7.4.3 php version and it is made by justin heilman and the best thing about laravel is a thinker using tinker you can modify your data without using any routes okay so here we are going to use a model so the model is located in app models then user okay user and then factory and then count we're going to create 10 users 10 dummy users and then create hit enter so you can see that we have 10 damage users in our users table so if you go to the level api then open users table you will see these 10 dummy users has been created now we can clear this now we need to make another to-do factory that is to do you can use a app namespace but you can also use to do so it will understand we are going to use that to do model and it will check for the alias for this and to do then factory and we can pass 50 right here then create hit enter you can see aliasing to do to app models to do for this tinker session so it created us 50 you can see the id is 50 and the created by 2 you can see the random regenerated as well as completed zero then completed one okay now if you if you visit your naraville api database then open the to-do's table you will see this 50 entry has been uh populated in our database so if i make this as hundred so our 50 entries inserted by this tinker shell we have used the factory and now you can clear this and you can type exit and hit enter to exit from the tinker shell now here we just need to go laravel api then go to ease and we can copy this and in our postman we can use the email send it okay undefined variable token in our auth controller dot php so in which 43 line number 43 [Music] there was a typo so you can see the token is right here and we have this token type error and we have the token validity 864 000 which is in a second so if i search it in our google so at seconds so 864 thousand seconds to hours which is two for 24 hours so one day okay and token type is bearer but if we make this as wrong like this one this says error unauthorized okay and you can replace this and send it we have this token now if we uh we can duplicate this duplicate tab and then we can use get parameter and we need to see auth user an auth profile and then we need to send this but it will show another or unauthenticated message because we didn't specify this token so in two way you can use this so the way is token in three way we can use this token so token this parameter you can pass send it so you can see the current user and another thing you can use is a post method you can use body so let's see if can send it as token and paste it let's see if it's work or not okay it's working but if we make this none an unauthenticated okay so i'm just going to remove this and we can also use another method that is authorization header you can use this bearer token then here you can paste it and send it you will see this user information okay now if i duplicate this tab and then if we want to uh refresh get a refresh token with a post method so you can see we have this token now as the refresh to um as the token has been generated so if you use the previous old token you will see an authenticated message because our previous um token has been removed and our new token has been generated so you can copy this and paste it right here now if you want to log out so log out so send message is unauthenticated [Music] to authorization you can pass it right here send okay user logged out successfully now we need to see if register is working or not so for this we can duplicate this tab and we need to make it as register and from the body you can use form data or raw as json format and email and we are going to use name as srijit and then here test right gmail.com now here if you can see if i say press send button it will not work validate require radiator okay this is not working so let's see in our earth controller validator make request all okay validate this should be required and made it required so save this file send so the password confirmation does not match so you also need to use password confirmation is password okay now if i uh delete this if i send this see this uh validator saying that the name field is required the email feed is required the password field is required okay now if i send this right now user created successfully this one okay so if i send again the email has already been taken now if i log in with this test at the rate gmail.com send you can see we have this token generated from the server so here we have this endpoint so far now we can login again and copy this token and paste it here and here also and you can make this as auth where now we are going to use a to-dos and then this should be get an authorization sent you can see all the to-do's which is which is created by uh you currently log logged in user so we have this two to-do's and then we can duplicate this we can use post method to create a new uh we can use form data or raw uh raw json format so here title and the title is this is a title uh second thing is description or not description body body is going to be this is a body then completed is false okay now if i send it let's see what happens status true to do title this is a title so if i go to that this this end point to those end point send so we have another thing that is titled this is a title but we can't see the current id of this to do so we can change it so go to the to this controller and after the to this controller here we need to pass an id parameter also okay send we have this id 41 43 and 51 so we can create a new so we can create a new uh to do so we can also update to do so we can duplicate this tab and then you can make this as put then to do's and then the 43 i think so let's see 41 43 and then we need to use our body the title is this is a title completed is true and let's see 43 is completed 0 and you can make it as uh title edited body edited send so you can see we have the status true and it output the current updated to do so if we go to the get parameter so 43 title edited body edited now last thing need to delete this 43 so duplicate and then make it as delete and body is none and if i send this status to 43 title edited this is going to be deleted now if i go to the gate so right now it is 43 if i send it so 43 is gone so in this tutorial we have learned how to make a laravel api using jwt authentication and you have also saw some cool things like tinker factory method also um how to create resourceful controller uh using mcr option when you are going to create a new model so it is there are lots of cool things in laravel so thanks for watching hope this tutorial will help you uh please subscribe my channel for the upcoming video tutorials and don't forget to like this video if you think it helps you thanks for watching
Info
Channel: Surajit Basak
Views: 25,095
Rating: undefined out of 5
Keywords: Laravel RESTful API, Authentication with JWT, JSON Web Token, Test API with Postman, Build CRUD API, techcetblog, Laravel, tymon/jwt-aut, Laravel 8.x, Lumen
Id: dFAlCnSjqtY
Channel Id: undefined
Length: 59min 10sec (3550 seconds)
Published: Mon Sep 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.