Laravel 10 tutorial - Build a REST API from scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this section we'll learn how to build a restful API using layer level 10. we'll start by creating crud or create read update and delete functionalities then in the upcoming section we'll Implement sanctum in our API alright let's open up our terminal and create our new project I'll come back when it's finished once it's finished let's CD into our newly created project then I'll open the project in the visual studio code editor here I'll start up the laravel built-in server then I'll go to my browser then enter a local host 8000 just to make sure that the laravel project is running properly and you will see the layerable landing page displayed on the screen the next thing that we need to do is to set up the database connection so let's switch back over to our editor then open up the dot EnV file here I'm going to use my SQL database so I'll leave all of these things except for the password since I have a password for my database next let's create a new database for our app let's copy the database name from here and here I'll use my SQL CLI to create my database feel free to use any MySQL client tools you prefer so let's switch back over to our terminal I'll open a new terminal window then create a new database using this command I'll hit enter key enter my password then hit the enter key again okay everything seems good now to verify if our database connection is working properly let's execute this command PHP Artisan migrate it seems that I forgot to save the last change so let me save this then execute this migrate command alright in this video we created our new layerable project and then set up the database connection for our project let's move on to the next video and see how to create our first model migration and Factory for our project in this video we will create our first model migration and Factory for our app the models are responsible for representing business data and logic a model object is responsible for retrieving and persisting data in a certain table for creating the table itself you may use any SQL client tools such as phpmyadmin table plus SQL Pro or other tools although using them is more convenient using migrations is much better migrations are like Version Control for our database they will track all histories of our database structure and if you're working with the team then migrations allow you and your team to have the same database structure so your app will work properly then to populate your database tables you may manually insert some fake data using any SQL client tools and again laravel provides a better way of doing that through model factories alright let's open up our terminal and create a model using the artisan make model command then we specify the model name or in layerable 10. we can omit the artisan make commands input just like this then hit enter here I got a prompt asking me about the model name in my case I'll create a task model hit enter and I got another prompt asking me if I want to create these things Factory form requests migration policy resource controller and Seed in my case I'll enter one since I want to create all of these things as you can see here it created the task model task Factory created tasks table migration task seater store task requests update task request task controller and task policy now let's open up the create task table migration here in the up method let's add the necessary columns for now we'll add a name column and a type of string another column will be is completed and it's going to be Boolean and we'll give it a default value of false next let's open up the task Factory here in the definition method declaration let's map the column names with values the name column will be filled with the fake sentence and for his completed column we'll set it with a random number between 0 and 1. next let's go to The Cedars folder and here we don't need the task seeder file so let's get rid of that then let's open up the database seeder file inside the run method let's clear everything then we'll generate 10 tasks like so call the task model then import its namespace then call Factory specify the number Then followed by the create method call alright let's give this a save switch back over to our terminal then migrate our task table migration and see the tasks table by calling the migrate seed command OK let me go to my database and see the task table as you can see the tasks table has been populated with 10 records in this video we'll create our first API endpoint alright let's go to the app folder then go to http and then controllers folder inside this folder let's create a subfolder API then inside the API folder let's create another subfolder B1 here we have a task controller which placed inside the controllers folder now let's move this file to the V1 folder let's open the file and adjust the namespace since this file has a different namespace from the base controller let's import the base controller's namespace OK let's go to the index method declaration let's remove the return type then inside the method let's return all tasks that we have next let's define routes for our API endpoint let's go to the routes folder then since we will Define routes for API let's open up the API file inside this file instead of defining a single route for our index action let's define resource routes for our API endpoint using the API resource method the path will be tasks and the controller will be task controller let's also prefix the route path with V1 you may add it here however since we may Define other routes in the future let's put the V1 prefix in a route group like this and now we put our task route declaration inside let's give it a save head over to our terminal and see our route by running this command as you can see we have resourceful routes for the task let's now access the tasks index endpoint in our API client tools you may use any API client tool that you prefer in my case I'll use Postman let me create a new collection inside the task collection let's add a new request I'll name it retrieve tasks the HTTP verb will be get then the URL will be http localhost colon 8000 API version 1. tasks hit the send button and here we'll get back a list of tasks in this video we'll learn about eloquent API resources as the name suggests eloquent API resource is useful when building API so it's basically a mechanism to transform your eloquent model into Json responses it acts as a transformation layer between your eloquent models and the Json responses that are returned to your applications users alright let's open up our terminal then to create an API resource we can call PHP artisan make resource let's call it task resource let's open up the file inside the resources folder then in the two array method declaration let's return an array and Define which attributes that will be exposed in this case ID from the task ID and then name from the task name and that is completed from the task is completed next let's head back to the task controller then instead of returning an eloquent collection like this now we'll return the task resource since we'll return a collection of tasks we call the collection method then pass the collection in don't forget to import the task resource namespace now while we're here let's go to the show method inside the method we'll return a single resource so we call the task resource since we'll return a single task we call the make method and pass in the task instance all right let's give it a save back to postman then hit the send button now we see our task collection wrapped in a data array and each task only contains ID name and is completed now for the is completed attribute let's go back to the task resource and Cassie has completed's value to a Boolean hit the send button again it's now in a Boolean value okay let's give this a save then duplicate the request let's change the name to retrieve a task then we need to specify the task ID here in my case it's going to be one hit the send button and here I get back a single task in this video we'll create another API endpoint that allows users to persist data to avoid unwanted data we also validate the incoming request to meet our requirements let's switch over to our editor then go to the requests folder here let's open the store task request in the authorize method let's return true since we don't want to perform any authorization next in the rules method let's define validation rules for the name column it's going to be required string and maximum character 255. okay that's it for now let's now go to the task controller since we're building API we don't need to define the create method so let's get rid of that then here in the store method let's remove the redirect response return type inside the method let's call the task model then save the incoming request by calling the create method and then pass in the validated request data the create method will return a model instance we can assign it to a variable after that we can return the newly created task as a Json response so let's copy the code from the show method now since we use the create method we need to mass assignable the column so let's go to the task model then specify the mass assignable column in the fillable attribute let's give it a save back to postman duplicate this request change the name to storing a task the HTTP verb will be post the URL will be API version 1 tasks then in the header we need to add accept key while the value will be application Json next let's go to the body choose the raw option and the format will be Json format for now we'll send an empty object to see if the validation is working as expected hit the send button OK here we get a 422 unprocessable content error which is the error that we expect and hear the error message the name field is required now let's enter the name here then hit the send button again OK the task has been created and we'll get back the newly created task in the last video we created an API endpoint to persist the incoming request now in this lesson we'll be adding an endpoint that allows users to update their tasks and another endpoint to Mark the task is complete all right let's switch over to our editor then let's first open the update task request since we need the same validation rules as the store task request let's remove everything inside the class then extend the class from the store task request let's get rid of the form request namespace import from here okay let's switch back over to the task controller here we don't need the edit method for our API just get rid of that and in the update method let's update the task by calling the task instance then call the update method and then pass in the incoming request that has been validated once updated we'll return it as a Json response so let's copy the code from here then paste it here and then remove the redirect response let's give this a save back to postman duplicate this request rename it to updating a task for the HTTP verb we'll need a put method in the URL we need to specify the resource that we'll be updating in my case 11. next let's go to the body section and for now let's remove the name to see if the validation is working as expected and indeed it's working let me put back the name and I'll update the task name to Task 1 updated let's hit the send button again okay the task has been updated successfully next let's add another endpoint that allows users to Mark the task as complete let's open up our terminal then create a new controller using the artisan make controller command let's hit enter the controller name will be API version 1. complete task controller hit enter again and here let's make it an invokable controller so I'll enter two let's open up the controller we just created inside the method let's type in the task model in the second argument import its namespace then remove the response return type then inside here let's update these completed attribute with these completed that comes from the request then to persist the change let's call the save method once it is updated we'll return the task resource let's import the namespace and then pass the task instance in last let's open up the API file and then Define a new route for our newly created controller it's going to be patch the route path is going to be tasks it receives an argument task then we'll be suffixing it with complete and the controller will be the complete task controller okay let's give it a save back to postman save the request change then duplicate this request let's rename it to Mark a task is complete here the HTTP variable will be patched the URL will be localhost 8000 API version 1 tasks task ID and then complete then in the body section let's send is completed with a Boolean value for now let's give it true now I'll hit the send button here the is completed is true if I now change the value to false then hit the send button again these completed now changes to false in this video we'll be adding another endpoint that allows users to delete their tasks let's switch over to our editor then go to the task controller here in the destroy method declaration let's remove the redirect response return type then inside the method we call the task instance followed by the delete method to delete the task from the database after that we'll return no content response let's give it a save back to postman then duplicate this request change the name to delete a task the HTTP verb is going to be delete then for the URL it's going to be API version 1 tasks followed by the task ID and here we don't need to send a request body so let's choose the net option let's hit the send button okay here we get 200 for response status so if we go to the retrieving tasks request then hit the send button we can't find the task with ID 11. okay that's it for now in this section we learned how to build crud or create read update and delete functionalities for our API let's move on to the next section and see how to make our restful API secure using Sanctum
Info
Channel: TutsPrime
Views: 20,630
Rating: undefined out of 5
Keywords: laravel api tutorial, laravel rest api tutorial, laravel api crud, laravel rest api for beginners, laravel tutorial, laravel 10 tutorial
Id: N9RKm7LJUjo
Channel Id: undefined
Length: 29min 59sec (1799 seconds)
Published: Wed Feb 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.