Laravel 11 tutorial 2024 - 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 restful API using LL 11 we'll start by creating CR or create read update and theet functionalities then we'll gradually add some other features such as authentication authorization and other cool features all right let's create a new lle project I'll call it Lal then hit enter let's select the no star kit option since we'll be using LEL for building API hit enter we won't do any unit testing for this project so I'll leave it as it is then hit enter I'll s like no because I prefer to initialize the G pository manually however you may select the yes option if you want to install the get poory automatically for your project I'll hit enter again okay I'll come back once the dependency packages are downloaded next we need to choose the database for our application you may choose any database that you prefer in my case I'll choose my SQL here I got another prom default database updated would you like to run the default database Migra questions I'll choose yes then hit enter now lall we assume that the database name is the same name as our project name since I haven't created the database yet here I got this warning message here I'll choose yes then hit enter once the database is created L we then generate the default migration for us okay let's CD into our newly created project then I'll start up the LEL build server by running the PSP Ron serf command once the server is running I'll go to my browser then enter Local Host 8,000 just to make sure that the level project is running properly okay here we see LEL welcome page display on the screen now if you're using her or valet you may not need to run the PSP belon server just enter your project name followed by Ault test and here we see the same L lending page all right in this video we created our new aable project and 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'll create our first model migration and Factory for our app the models are responsible for representing business data and logic a model object is used for retrieving and processing data in a certain table now for Crea tables a common way is to use SQL client tools such as PHP mmin table plus SQL Pro or other tools although using those tools is more convenient using migrations is much better because migrations are like Version Control for your database they will track all histories of your database and if you're working with a team migrations allow you and your team to have the same databas structure so your app will work properly for everyone then to populate your database tables a traditional way is to manually insert some fake data using any SQL client tools but LEL provides a better way of doing that which is by using model factories all right let's open up our terminal and create a model using the arson make model command then you may specify the model name or since Lal version 10 you can omit the model name 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 table hit [Music] enter now I got another prompt asking me if I want to create these things it'll be C Factory from requests migration policy and resource controller for this case I'll choose all options except for dater as you can see here it created task model task Factory cre task stable migration store task request update Tas request task controller and task policy now let's open up the create task table migration here in the app method let's add the necessary columns for now we will'll add a name column in a type of string another column will be is completed it's going to be bullan and we'll give it a devil value or false all right we have defined a table structure in a migration file let's Now work on the alant factory so that we can easily fill the table programmatically 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 a effect sentence for is completed column we'll set it with a random number between 0 and one next let's go to database C folder then open up the database C file inside the run method let's clear everything then call the task model import its name space then call Factory specify the number number Then followed by the create method [Music] call right let's skip this save switch back over to our terminal then migrate our task table migration and fill it with some fake data by calling this command PSP oron Migra with a sid option okay let me go to my database and see the tasks table as you can see the task table has been ped with 10 records in this video we'll create our first AP in point right let's go to the app folder and then HTTP controllers folder inside this folder create a subfolder API then inside the AP folder let's create another one V1 or version one here we have a task controller which inside the controls folder directly let's now move this file into the V1 folder let's open up the file and adjust the name space since this file has a different namespace from the best controller we need to import the base control name space it's from App HTTP controllers folder okay let's go to the index method declaration then inside the method let's return all tasks that we have don't forget to import task model name space pH next let's define a route for our API in point let's go to the routes folder since we're going to build API we'll Define our routes in API file however in L 11 the API route file are no longer available by default if you're using Lal 10 or below you'll find the file inside the folder so to add a file and other API stuff let's head over to our terminal and then run PSP Ron install colon API let's H enter syum package is installing the AP Ro file published and then I got another prompt one new database migration has been published would like to run all pending database migrations I'll answer yes and then hit enter as you can see it run the create personal access token stable migration and API scolding insult okay let's open up the API file inside this file instead of defining a single route for our index action let's define a resour route for our AP Point using the API resource method the path will be tasks and the action will be task controller don't forget to import the controller name space let's also prefix the road path with V1 you may edit here however since we may Define other routes in the future let's put the V and prefix in a rrop like this and now let's put our tou Rod declaration inside let's give it a save head back over to our terminal and sa our routes by running this command as you can see now we have resource Pro routes for the task let's now access the tasks index end point in our AP client tool you may use any API client tool that you prefer in my case I'll use posman let me create a new collection insert the task collection let's add a new request I'll name it retrieve tasks the HTP verb will be get and the URL will be HTTP Local Host colon 8000 AI version one tasks let's hit the send [Music] button and here we got back a list of our tasks in this video we'll learn about eloquent EP resources as name suggest Elon API resource is useful when building API it acts as a trans information layer between your eloquent models and responses that returned to your application users all right let's open up our terminal then to create an API research we can call PSP or S make resource then specify a resource name an main convention is to prefix the name with a model name and suffixing it with resource so in this case task research once created let's open up the file inside resources folder so each resource class contains a toay method which returns an array of attributes that should be converted to gon when the resour is returned as a response by default it calls the to Method from the parent class now let's replace it by retur an array then Define which attributes will be converted to this one in this case ID from this ID note that we can access the model properties directly from the this variable this is because a resource class will automatically proxy property and Method access to the underlying model for convenient access let's define name from task name and then it's completed from the task is completed okay with this resource defined let's head over to the task controller then instead of returning an Elon collection like this now we'll return the task research we import the name space since we'll return a collection of tasks we call the collection method then pass the collection in now while we're here let's go to the show method inside the method we'll return a single research so we [Music] call the task research 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 passman then hit the send button now we see our task collection wrapped in a data array and each task only contains ID name and it's completed now for this completed attribute let's go back to the task research then cast this completed value to a bullan hit the same button again is now in bulland [Music] 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 APN point that allows users to persist data to avoid unwed data we also validate the incoming request to meet our requirements all right let's switch over to our editor then go to the request folder here let's open the St T request in the authorized method let's return true since we don't want to perform any otherization next in the rules method let's define validation rules for the name column is going to be required a string and maximum character 255 okay this is for now let's now go to the task controller since we are building API we don't need to define the create method me so let's remove it then in the store 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 so we can assign it to a variable after that we can return a newly created task as adition response so let's copy the code from the show method now since we used the create method we need to must assignable the column so let's go to the task model then specify the mass assignable column in the failable attribute let's give it a save back to pman duplicate this request change the name to storing a task the HTTP verb will be post the URL will be API version one tasks then in the header we need to add accept key while the value will be application gon next let's go to the body just thew option and the format will be this format for now we'll send an empty object to see if the velon is working as expected hit the send button okay here we got a 422 unpressable content error which is the error that we expect and here the error message the name field is required now let's enter the name here then hit the send button again okay the task has been created and and we got back the newly created task in the last video we created an APN point to proce the incoming request now in this video we'll be adding a new endpoint allows users to update their tasks and another point to M the task as 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 stas request let's remove everything inside the class then extend the class from store task request then let's get rid of the form request name space 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 jent response so let's copy the code from here and then paste it here let's give it a save back to pman duplicate this request rename it to updating a task for the HTV verb we'll need a put method in the URL we need to specify the resource that will 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 change the task name to task one updated let's hit the send button again okay the task has been updated successfully next let's add another in point that LS users to Mark the task as complete let's open up our terminal then create a new controller using PSP Ron make controller men let's hit enter the control name will be API version one complete task controller hit enter again and let's make it invocable controller okay let's open up the controller we just created inside the method let's type hint in the second argument the task model don't forget to import the name space then inside the method let's update the this completed attribute with this completed that comes from the request then to puras a change let's call the save method once it is updated we'll return to task resarch don't forget to import the name space and then pass the task instance in the make method last let's open up the API file and then Define a new route for our nearly created controller it's going to be patch the Earth path is going to be tasks ites an argument task then we'll be suffixing it with complete and the action will be complete task controller okay let's give it a save back to pman sa the request change then duplicate the request let's rename it to Mark the task as complete here the HTTP verb will be patch the orall will be Local H 8,000 API version one tasks task ID and then complete then in the body section CL s is completed with a bullet value for now let's give it a true okay I'll hit the send button here this completed is true if I now change the value to false then hit the send button again okay this 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 dist method declaration let's call the task instance followed by the delete method to delete the task from the database after that we'll return no content response as SK is save back to pman then duplicate this request change the name to delete a task the htb verb is going to be delete then for the URL it's going to be API version one one tasks followed by the task ID and here we don't need to send a request body so let's choose the non option let's hit the send button okay here we get a 204 response status so if we go to the retrieving test request then hit the send button we cannot find the task with ID 11 okay this is for now in this section we'll learn how to build crra or create read update and delete functionalities for our API in this section we'll be adding a new feature that allows the end users to prioritize their tasks all right let's start by cre creating a new model with a migration let's open up our terminal then create a new model I'll call it Priority with the m option okay once created let's open up the migration file then inside the app method let's add a name column in TP of string and unique let's also add another column in a string called description I think that's all we need now let's fill the table with high medium and low priorities I think we don't need to add other priorities in the future so let's do that here let's call the DB facade don't forget to import it from eliminate support facets followed by the table method specify the table name priorities and then call the insert method ins the method let's pass an array insert the array let's add add another array specifying The Columns with values okay let's toate this and adjust the values all right with this table structure defined let's make another migration back to terminal then make another migration I'll call it add priority ID to tasks let's open up the file in the method let's add a foreign ID called prior ID and then constrain let's make it nullable and then place the column after this completed column next let's go to the down method and then drop the priority Ed column don't forget to drop the frame Key by calling by calling the D and then specify the frame ke constraint name which is based on the name of the table and the columns in the constraint followed by uh undor forign suffix in this case tasks priority idid and then forein or we can also use this way I think it's much simpler all right with this change let's now open up the task model then in the failable attribute let's add the priority ID column let's also Define a relationship method to the priority [Music] model next let's open up the task Factory and then specify the priority ID so we'll randomly set the column with a null value or a random priority ID okay the next thing that we need to do is to update the store Tas request so let's open up the file then add validation rules for the priority Al column it's going to be n and its value should be exist in the priorities [Music] table okay let's also Define the attributes method and then custom the column name [Music] in this case priority ID is going to be priority next let's make a new a resarch for the priority let's go back to our terminal and then create a new resarch let's open up the file and then Define which attributes will be converted to gon next let's open up the task research then add a new attribute priority the value comes from Priority research make and then specify the priority relationship we can also use the one loaded method to conditionally load a relationship this method accepts the name in this case priority okay let's give it a save back to our terminal and then run PSP Arison migrate fresh seed sorry I made a typo PSP oron migrate fresh with it option okay okay let's now go to posman then go to staring a task request I'll change the task name to task priority and then specify priority ID but let's set it with an existing ID let's hit the send button column not phone priority okay let me go back to stus request and specify the column in here should be ID let's hit the send button again we get the expected error message now let's change the value to existing priority ID and then hit the send button again now the task has been added successfully however we cannot see the priority attribute to do that let's go back to our editor then open the task controller for now let's open up the task controller in V1 folder then go to the store method to include the relationship on the task research let's load the priority relationship like so you to save switch back to posman I'll adjust the name and priority ID then hit the send button again now we see the priority attributes in the response body let's now go to retrieving task request then hit the send button we can see the prior attribute so back to our editor then go to the index method so to load relationship in a single model we use the load method however for the collection we use the with method and then specify the relationship name don't forget to replace the old method with a get method let's have a look okay now we see the priority attribute in the response body
Info
Channel: TutsPrime
Views: 9,542
Rating: undefined out of 5
Keywords:
Id: BOWrfvHeE4A
Channel Id: undefined
Length: 46min 53sec (2813 seconds)
Published: Mon Apr 08 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.