How to make secured rest api in laravel 9 | Rest API in Laravel 9 | Laravel 9 API Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome to tech tool india in this video i am going to explain all about laravel 9 rest apis i'm going to explain crud operation with the rest apis i'll show you with the examples you need a basic setup for installing level 9 if you want to know how to install level 9 you can click on the i button and check out the video i have put a link in the description as well so without wasting any time let's get started i have installed a fresh laravel 9 as you can see the current version is reliable 9.6 so in this video i'm going to take a example let's call it a post which will accept two parameter title and the description so to do that let's open this in our code editor so it is a fresh installation i need to configure the database first let's go into the database i have already created a database called laravel api so i just update this database what next we need to create a model which will accept a title and a description for post so let's create it you can create it by running php artisan make model call it as a post and give it a hyphen m to create a migration for this as soon as you create this you'll see this has created a file for migrations if you go to the migrations you'll see this create post post migration here what we need to take we have a field called title give it as a string name it as a title the second field which we are taking is a description for the post i am taking this as an example you can take any other fields which you want all right so we have made our migration ready what next let's migrate it and see if it is migrated successfully by running a command php artisan migrate it will migrate our database yes it's been migrated let's go into our database and check if all the tables are there yes you can see this posts table which includes title and the description all right now let's go to the post open the post model let's close this go to the app models and post dot php here we need to define our fillable property in order to use a mass assignment so i'll use protected dollar field label and define two properties title and description all right so we have our property defined as a fillable here the two fields which we want to mass assign next we want to create a controller for that we need to run a command php syn me controller i'm going to create a folder called api for all the apis and just creating host controller and i can pass a model post so the controller has been created successfully if you go to the http controllers you'll find api folder inside it you'll see a post controller and our post model is already used in this controller all right so we have defined our post model we have created our controller the very next thing is to define and this post controller comes with all the basic red function which is like index function create function store show edit update and it'll destroy so these are the crowd operation which we are going to see today so let's define these roots in our apis let's go go to our roots epi.php for this uh tutorial i'm not going to use any authentication it's just a simple tutorial without any authentication so i'm going to define this root and i'm going to call it api resource i'm name it as posts and call its controller this should be fine all right so if you want to see what routes we are available so you can just write in a command php addition root list if you see this api roots you'll see all the apis last boost are available here inside epa you see these are the redirected to this api post controller function respective functions so the routes are all set for the apis so the next thing we want to test this route so i'm going to use postman for our http client testing you can use any other http client or you can install uh extension on vs code you can use that but for now i'm going to use a postman for testing all our http client request so i'm just going to clear this and next let's go to the postman this is the valley url which i have set up for our project if you go to the this you will see laravel epa.test this is a local url i have set up on this url if i just write this api slash posts if i hit this url now you'll see you are getting a 200 response but you're not getting any of the data the reason being we are not returning anything here so i just to seek of uh our preview like it's working or not i'm just going to written a json response here written response json and in that i'm going to pass a status true and posts would be just a blanket let's go ahead and hit our api again you see you will have a status true post is equals to blank so our apis are working the next thing is to create a post and then get the response so i'm going to add a new tab here just copy this post use this so if you go to our route you'll see to create a post the end point is epi slash post but the method is post so it will hit our post dot store function let's make it a post and in a body let's pass a json object here which includes a title this is first post and a description this is first description this first post description i'm taking as example so now we are using our post method to store the post let's go into our function to validate it i'm going to create a request here by just running a command php rtc make request store post request so if you go to the app http requests folder you'll see this store post request i'm just going to authorize it always true and inside a rule what we want to put we want a title title should be a required field so this will be required and the maximum value for this is 70. next thing is a description description would be a required field all right so we have created our request so to store this instead of request i'm going to use this store post request as i just use this store post request it includes here on the top you need to use this as app http request and store request then you can use here directly on the store function so what is what this is going to do this is going to validate all the requests coming to this function and if validation fails it will written a validation error to see our validation i just added this store post request in the store function and dumbed all the data let's see if this is working or not let's go in our postman so before sending this api we need to add few headers in order to send a json data and get a response in a json so we'll add a header call is accept put it as a json and contain type also the contain type of this response request would be json so the request and response should be in the json that's why we i'm sending this accept and contain type as a header in a body i have just put this like only uh title i'm not sending the description if i send this response request you've seen the response the description field is required that means our validation is working properly let's add a description here give it a comma here and add a description test post only so i just added a random description and let's see if it is working now yeah it's working now if you just review this i have dumped the title i mean whatever we are getting on the request so we are sending the title and description and that's exactly what we are dumping in the controller let's go in our controller as you can see we have just dumped this data let's store this data by post create uh give it as a post is equals to post create and whatever we are getting in the request and in order to return this just written response json and give it a array call it status true and post is equals to post which we have created and here let's pass 200 as its success response and you can add another parameter called message and give it a post created successfully all right let's go to our postman now let's send this you see we got this status as true post created successfully and with all the post data all right so we are getting this response let's go ahead and update our update function so in update also we are going to use store request store post request as a store validation and we are using this post so what we are going to do the just update it whatever the parameter we are getting request of all and just returning the same response as we have written in a create just instead of create let's see update it successfully let's create create a new tab i'm just going to duplicate this tab and this time i have to add a put method here and and pass the id of post if you go our root list you'll see to update this we need to put api slash post slash post post is stands for post id so it will automatically associate this id with the post model so as we know the id is one so i'm just passing this up one and we don't want to change anything in header let's go into the body and see it update it and call it update it all right let's send this request and see what we get in the response as you see we got the post updated successfully and if you see the id is one and we got our title and description updated so this is a working as well let's go to the destroy function as this will just delete the response so you'll see like post pointing to delete and then written the response and instead of passing the post just pass this message and to delete it method should be delete and the urls should be the same let's go and duplicate this tab uh we don't want to pass anything in the body method would be delete here let's send this as you see post deleted successfully so we have completed this create update delete let's create an another one we have created this here now let's get update this post here let's take a post function post variable and just pull all the post here and put it here in the variable all right if you now hit the get epi for the post you'll see you have oh let's create another one here and see if we are able to see that in a get response you'll see we have two posts available all right so i think we have covered the basic thread operation of apis it's very simple uh what we have did till now i'll summarize it quickly we have created a post model with the title and description we have created the migration migrated the table and then we have created this post controller with all the basic cred functions and we have used this index function uh in a store function we have created the store post request which will validate our data with the title is required at maximum 70 and the description will required in this and then we have defined our api resource here in the epa.php file and we have taken all the function here in the post controller and in a store function we have just stored the data and written the response similarly we did on update we just updated the data and returned the response and similarly on the delete india in this video i am going to explain you about laravel api's authentication for authentication we are going to use laravel sanctum in this video in level 9 laravel sanctum comes in built with composer if you go to the composer.json for laravel line you can see this laravel sanctum is required as a dependency but if you are using any old version what you need to do you need to go to laravel sanctum documentation and you just need to install this dependency via composer and after installing this dependency via composer you just need to publish the service provider after that you need to run a migration which will create a table called personal access token this table is used to store the token for each user level sanctum allow to create multiple tokens for each user by which we can define the scope of the user for that particular token so let's get started and see how we can use this laravel sanctum in level 9. we have already installed laravel line apis and made the cred operation if you go to the apis we have create a post api's get api and if i hit this i'll get this to response of the post so right now it's an open api there's the new middleware for authentication anyone can access this api in order to write the middleware or author authentication for these apis we need to create an authentication controller in order to create a token for each user for that what we'll do we'll go to the apis we'll create two we'll create one controller for authentication of the apis by running the command php artisan make controller api will make auth controller for all the api's authentication route let's create this if you see this creates auth controller we need to do tool now we need to define two routes for register and sign in so we'll create one register root call it auth register and give it a controller auth controller so we need to use this auth controller you can see i have imported this auth controller via auto import you can use this auth controller on the very top of the page and use this class next we need to define which function we want to use for this so we will call it create user we have defined our auth register root the next is auth login root and we'll call it login user so we have defined these routes next we need to create this controller function let's go to the controller and let's define create user request so we'll just simply put it as a request and request parameter let's create this by creating a function name create user which will accept request as a parameter all the form requests will come here what we need to do next here we need to validate the request in order to validate what we'll do we will create a validate user validate user and what will right here and as soon as i use this validator you can see on top of controller we have validated use the validator class and i'll pass here the data data is all the data which is coming through request the rules next we need to write the rules rules will be we required a name parameter which is required there should be an email parameter which again is a required parameter and it should be an email next is it should be a unique of users table column should be email and since it's a create request we don't want to accept any ids here all right so we have written this for email the next should be a password always required for a user so we'll just simply put it as a required next if this validation will fail we need to return a response of error with json so we'll simply check this validate user if this fails so we need to written a response json response will simply follow our response like status should be a false message should be validation error and there should be all errors in array like validate user errors so this will hold all the errors and the response code will be 4 not 1 so this will be our validation before moving ahead we need to put all this inside a try catch block i'll just move quickly this in a try block so that we can cast the response and written proper handle proper catch if we found anything so the message will be whatever the catch message will be here we'll simply use that get message and we don't want this all right so we have validated our input next what we need to do we need to use we need to create a user so to create a user what we are going to use the user model inside this we have to pass all the parameter which is coming through request so we have a name email and password so the password should be used as a hashed password so for that we are using as make and the value will be the request of password so this will be this will create the user so in order to import use this user we need to import the user model and in order to use this hash we need to use import this hash facade here so we have imported hash we have imported users we have imported the validators so three imports will do all this here once the user is created what we need to do we need to return the user with api token in order to create the token with sanctum as sanctum isn't built in laravel 9 we need to use has api token in user model so let's open and if you go to the user model you see this has epi tokens this is a trade clause based on the laravel sanctum what it does it actually opens a function called create token which will create a token for this particular user so the next thing we need to return a response will simply copy the above code for response and update it based on like it's a 200 response stated should be true message should be user created successfully and the token should be now we need to return a token so what we'll do we'll use this user and then we'll use our create token method create token and in that we need to pass what kind of token it is and it should be a plain text token all right so this will return a token let's save this let's go to our let's test like how this function should be working let's test this function to test this we need to use this auth register in apis so we'll create a new will use a post method we'll put this copy the url from here paste it here after api we need to use auth register inside a form data what we need to do inside body we need to pass the form data and here we are passing the name email and password password would be all right so we have this auth register apis to test let's send this request as you can see we got the status as true user got created successfully and received token next what we need to do we need to test if this particular user can be authenticated by using this token for that if you go to the post right now it's an open api anyone can access but as soon as i apply a middleware here middleware for auth earth and auth using sanctum so i as soon as i apply this and go to this api and hit it you see this call this is calling it unauthenticated and giving it response 401 unauthorized for this we need to pass a br token authentication and in that if i put this token i just copy this token and put inside our bearer token let's see if this is going to work for us it's working so as you can see as soon as you apply this middleware earth sanctum the token is required if you do not pause pass the token it will give you authentication error as soon as you put the token it will pass the request and give you the response so it's very simple as we did on the register we need to create a login user function in auth controller in order to create token while login so what we need to do log in the user will create the function name it login user use the similar request as a parameter use the try catch block as above copy this response type here in the catch block and put it here in the login again we need to validate a user so what we'll do here we just copy the same validation and just remove this name parameter from here because in login we just required only email and the password if there is any validation error this will happen in order to check a login credential what we need to do here we need to use auth attempt by using auth attempt if there is a invalid credential it will give you a false response so what we are going to use here we will check if auth attempt giver false response we need to return a response with error of wrong username and password or email and password so what we'll do we will only take email and password so here we need to pass an array of email and password so this will take only email and password and if this attempt fails and what then we need to return a response saying username or password does not match right so we need to give this response and if it pass then what we need to do we need to find the user which will be email should be the request of email and this should be first if it is passed like if authenticated then we need to create token again so the similar response will be returned after authentication so what we will do here we will return this the user logged in user logged in successfully and then we'll return the api token so this should work for login let's test this as well let's go to our postman duplicate this request tab and inside a body we need to pass email and password instead of register we need to test our login let's send this great this is also working let's test this token go to our first remove this send this it gives you the unauthenticated put it out token send the request it gives you the response so that's it that's how we can create a sanctum authentication for the epis it's really very easy we just need a root for registering and creating api token for those users and wherever we want to put this sanctum authentication method middleware it will just apply the sanctum authentication middleware and restrict any open user to access your apis hope this video will be informative for you if you found this video informative please do subscribe our channel like this video share this video with your friends if you face any issue while integrating this sanctum in your project please do let us know on the comment section till the next video keep watching keep learning thank you for watching [Music] you
Info
Channel: TechTool India
Views: 5,470
Rating: undefined out of 5
Keywords: laravel api, laravel, laravel rest api, laravel rest api for beginners, laravel api tutorial, laravel 9, laravel rest api authentication, how to build restful api using laravel 8, how to build crud api in laravel 8, how to make an api in laravel, laravel api with react, how to build a project with laravel and nuxt, laravel rest api tutorial, create a rest api in laravel, rest api laravel, rest api laravel tutorial, rest api, laravel 8 api rest
Id: FZL-T2gu-XA
Channel Id: undefined
Length: 40min 19sec (2419 seconds)
Published: Thu May 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.