Introduction To Eloquent | Laravel 8 For Beginners | Learn Laravel 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys my name is dari and i hope that you have a wonderful day now that we have talked about how to build queries we're ready to take another step forward and talk about eloquent eloquent is an orm and like i said before orm is an object relational mapper which also means that it's a database abstraction layer that provides a single interface to interact with multiple database types a single eloquent class is responsible for not only providing the ability to interact with the table as a wall but also representing an individual table row and this might sound pretty difficult to keep it simple eloquent has one primary focus and that simplicity keep that in mind whenever someone asks you why eloquent just respond with one simple word simplicity i can scream that it's simple but why just like the rest of blauraval's framework it relies on convention over configuration meaning that it tries to build something with minimal code i have created a new project called cars and i want you to do the same i want to retake a couple steps that we've done so far so let's hop to the cli and what i want to do is to require tailwind for our ui so let's say composer require laravel dash front end dash presets forward slash tailwind css space double dash dev hit enter this might take a second so i will pause the video so let's install npm so npm install and npm run dev this might take a second as well so what's next we need a controller a model and a migration we could perform them all in one single command but that's not what i prefer i usually make my model and migration in one command and my controller in another so let's say php artisan make me a model called car m so the migration flag and you can see that our model and migration have been created so let's create a controller let's say php artisan make me a controller called cars controller and i want to add a pretty cool flag that we haven't talked about and that's the resource flag so let's say double dash resource whenever you want to create your parts functions you need to create them manually right you need to create a method to show the cars to update the cars to delete the cars and so on so what we could do is to create them automatically let's hit enter you can see that the controller has been created that's up to visual studio code and let's open our controller all right and as you can see we have our index create store show edit update and destroy methods in most cases laravel research routing assigns the correct routes to a controller now what we do need to do is to create a route so let's do that let's open routes web.php without the resource slag we use the route like this right let's get rid of it what we could do right here is to basically say route again double colon but instead of saying get or something else we could say resource the idea behind it is exactly the same what is our first endpoint well forward slash comma what's our controller cars controller double column class now let's pull in our cars controller let's say use app backslash http backslash controllers backslash cars controller let's save it let's hop to itune because i want to show you something pretty cool let's write down php artisan route column list and what this basically is is all our endpoints for the methods that we have in our controller we have an index store endpoint create endpoint show update destroy and edit so what we've done inside our web.php is basically saying well our first endpoint is the forward slash and then we want to pull in and then we want to pull in all the methods that we have in our cars controller so let's go to our cars controller let's scroll up to the index method let's return a view to index you see the difference we don't need to define every single route in our web.php file instead we've defined them in one single command so right now let's open our views so resources views let's delete the welcome page because we don't need it let's create a new folder in here called cars and inside our cars let's create a new file called index.blade.php in our index.lit let's just write down cars oh yeah and obviously we need to change our endpoint to cars so forward slash cars the forward slash was just to show you what the first endpoint could be let's go to chrome refresh it and cars have been printed out all right i want to create a ui where we could perform eloquent stuff so for that i obviously need a ui but i don't want to create anything fancy at the end of this course i will add some projects with a way better ui but for now let's hop to our visual studio code let's create a new directory inside views called layouts oh my bad let me rename it for a second now let's add a app.blade.php where we will place our core html so let's write down doc alright let's create a section inside our body so add yield with the name of content let's put in our tailwind css that we have inside our public directory css app.css all right let me close that off actually because we don't need it let's go right below our meta let's say link the href is the asset method which goes to our public directory so css wordless app.css save it and since we have pulled in our tailwind stuff let's change the background color of our body let's set it equal to a class bg dash gradient dash 2-r from dash gray 100 to gray 200 and this won't work for now because we need to go inside our index plate let's get rid of cars let's extend the layout page so layout start app let's save it let's go to chrome refresh the page and i'm not sure if you can see it but the background color has changed a little bit so right now we're able to define our section so let's say add section and section the name of our section is content inside our content we need a diff another div and an h1 and the text of our h1 is cars give it a class of text 5 xl uppercase and bold and i won't go in depth about what everything means tailwind is very straightforward and i might create a course later on so the div that's wrapped around our h1 has a class of text center and the entire div has a clash of margin dash auto so m auto width is 80 so 4 5 and the padding y axis is 24. save it go to chrome refresh it and this looks alright now let's create the content that will eventually be inside the loop whenever we pull stuff out of our database so let's go to visual studio code right below our div let's say another div with a class of width 5 6 padding y is 10 and we have another div inside of it with a margin of auto so m auto so i want the year that the car is founded the name of the car and i want a paragraph so let's create that let's say span found it let's say 2020. the span has a class of uppercase the text is text dash blue dash 500 font bold text is extra small and it's italic save it go to chrome let's actually wrap this inside the diff with the margin auto as well so let's copy this one let's face it right here align it a little bit so what do we need next well right below our span i want an h2 with the name audi it has a class of text dash gray dash 700 and the text is five excel chrome refresh it all right right below my h2 i want a paragraph and let's create some lorem ipsum text so let's write down lorem hit tab let's give our paragraph a class text lg tag status grade 700 and right below our paragraph let's create a hr so a line with a class of mt 4 margin top 4 margin bottom 8. save it refresh it now let's actually create a little bit more spacing around our paragraph so let's say py is six all right this looks good whenever you work with eloquent you want to interact with the database so let's set up our database by creating our first migration so let's go to the code editor let's open database migrations and it's the last one create cars table what i want to do is to change my id to increments and i want to give the name of id right below my id let's create a new table which is a string with the name name i want the year when the car is founded so let's say table table integer found it and i want the description so table long text which is the description let's save it but before we migrate our database let's open the dot emv file let's check our database for destroys my host is localhost my port is alright we will create our database username is root and my password is dory1234 this is the data that i need for now so let's go back to the command line because we need to go inside my sql and i already have it open what we could do is to create a database so create database cars one row has been affected and like before don't close off my sql because we need it later on as well let's go back to the other tab because now we're ready to migrate let's say php artisan migrate and we have a connection issue so i probably haven't saved my emv file all right let's run it again yes and it has been migrated as you could see so what do we need to do next well we need dummy data inside our database so let's go back to mysql let's create an insert query so we want to insert into cars the columns name founded and the description and the values are let's say audi it's founded in 1909 and let's give it a description of this is the description for audi let's close it off with the semicolon let's hit enter and one more row has been added let's change the second one to mercedes and the value of the name two and mercedes has been found in 1926 and the last one is let's say bmw bmw is found in 1916 and the name is bmw as well all right so that's desk cars again all right let's select everything from cars i forgot from all right we have three rows right now that we could use so my goal is to basically show you all eloquent models in order to retrieve update delete and insert data but before we do that let me show you a couple of things that we could add inside our model so let's hop to our car model let's open it if you took notice we haven't defined anywhere inside our code that the car model needs to interact with the car table in our database that's because the default behavior for table names in laravel is snake cases and it pluralizes your class name there is obviously a way to manipulate this and to give it a different name and to do that we need to create a new property so protected table and we need to set it equal to a string which will overwrite the defaults table called cars we don't need to do it so what i want to do is to set it equal to cars just as it is we could also manipulate the primary key so if we hop back to my sql now let's say desk cars you can see that the id is indeed the primary key of our table so we can change that by basically creating a new property so protect it called primary key and we can set it equal to a new table so we could say that our name is our primary key which makes no sense but we could do it now there might be a case where you just don't want your primary key in that case you can set the value of your primary key equal to false but what i want to do is to just set it equal to id just as it is so if we hop back to item you can see that we have a updated ad and created ad well if you don't want to use it you could create a new property called timestamps and you just need to set it equal to false but if you want to use it so let's say true you have the opportunity to customize the format and that can be done by saying protected date format is equal to the same as the php date syntax so let's say hours column minutes column seconds and once again these are all optional you can either remove them right now or keep it i will remove the date format because i don't want that now that we've talked about the model we're ready to talk about how we could retrieve data with eloquent and you can see this as a select query in my sql so whenever you want to retrieve all blog posts and print them out or you want to retrieve a user by checking the user's credentials or what we're going to do is basically retrieving all cards that we have in our database and send it back to a view this is something you will be doing most of the time you want to pull data from your database using the static call on your eloquent model so how do we get started let's open our controller let me actually close off everything because we don't need it yeah and we need our cars controller now the first thing that we need to do is to pull in our car model so at the top of our screen let's use app backslash models backslash car so a single model now what's next well we want to perform something like this right we want to basically say select everything from the table cars in eloquent we can create a variable let's say variable cars and let's set it equal to the model that we have in our case it's car followed by double calling and we want to get everything so we need to use a function called all before we continue let's die dump our wearable cars to see what the output is let's save it google chrome refresh the browser and we have an array let's open it and we have all cars right here now let's hop back to the code editor honestly it's not necessary to create a variable and set it equal to our eloquent model we could also pass the eloquent model right into the view but i think this looks a little bit cleaner than doing that so what i want to do is to add a comma right after our index we want to pass in an associative array cars pointer variable cars let's get rid of the dd and we don't need to select the reason why i'm passing it in as an array is because i want to loop over it in our ui so let's do that let's go to our views so our index.blade let's actually copy the entire div with the margin auto let's remove it let's go right inside of the div let's create a for each loop and that's for each over the cars that we have as a single car so let's paste in whatever we just copied all right let me align it and what i want to do is to replace 2020 with the variable car and i want to pick out found it as to the same thing for audi let's say car name and for the paragraph as well variable car i want to grab the description save it go back to chrome refresh it and apparently our die dump is still there so let's actually save this file and you can see that our audi mercedes and bmw has been printed out obviously there's also a way to filter through all cars so as you can see we have our variable cars which is equal to all cars but instead of saying all let's get rid of it and let's use the aware method so what do we want to achieve we want to see if there is a value in the column name that's equal to let's say audi and then we want to get all cars so let's go on the line below and let's say get let's save it let's hop to chrome refresh it and only audi has been printed out now this is how you get a specific value right now we're writing down audi right here let's say that a user wants to log in well you can grab their id and use it right here or whenever a user clicks on a specific product your endpoint will change and you can use that specific endpoint right here you may have noticed that everything that we're doing is basically the same as laravel's query builder and that is definitely true but you could do a lot more stuff so keep in mind that everything we did with the query builder on the db fake is also possible with eloquent objects as you can see we're using the get method right here which is exactly the same as a normal query builder call we're building a query and then we're calling the get method to get the results whenever you want to process a large amount of records so actually not what we're doing right now there might be a possibility that you run into memory or locking issues and since laravel is so great to use there's a method which allows you to break your request into smaller pieces so it will chunk it down so on the line below let's create a new variable cars and let's set it equal to car column column chunk the first param is the amount of rows where you want to chunk so let's say two comma function parenthesis curly braces inside their parentheses let's pass in variable cars and that's loop to root all of our cars so let's say cars as a single car print underscore r that car save it hop back to chrome refresh it you won't see any difference right here the query has been split into multiple queries based on the number that we have passed in right now it's two so we have four rows in our database then we're performing two queries of two rows what we've done so far was printing out stuff that has been found now there might be a chance where there is no model found and you just want to throw an exception for that we could use the find or fill and first or fail method it will retrieve the first result of the query let's get rid of our second cars variable we do need our where method but instead of saying get let's just say first or fail it will retrieve the first result of the query and since we have set it equal to audi everything will be fine so let's go to chrome and we're getting an error right now because we need to change something on our front end since we're retrieving only one single row so let's go to visual studio code the index let's actually delete the variables that we have right above our div and let's just print out variable cars save it refresh the browser and you can see that we have one single row where the name is equal to audi and we could also print out the name by saying pointer name which is equal to rd but what if we change audi insider where clause to something that we don't have so let's say tesla save it refresh the browser and we're getting a 404 because it does not exist there are a couple aggregates that we could use in eloquent as well so let's go in online below and let's say print underscore r a car where the name is equal to audi and return the count and cars with one r excuse me and let's comment out this one refresh the browser and you can see that the return value is one because we have one match instead of counting the match that we have we could get rid of the aware clause and say all so we want the count of all the cards that we have refresh the browser and the output is three we can print out the sum so let's get rid of everything after the double column let's say sum and well let's say they've found it which is an integer and we need to add an extra set of parentheses save it chrome refresh it and the sum of three integers is 5751 and we can print out the average so let's say avg instead of sum refresh it and the sum is 1917. now that we're done with retrieving data i want to show you how we could insert data and this is where you will see a difference from normal query builders and eloquent so let's hop to the code editor let's get rid of the average let's undo our comment let's just return all cars and now we're done with the index so we can proceed with the create method so inside the create method let's return a view to cars.create we basically need a form which will allow us to insert data into input fields click on the submit button and do something with it inside the store method so what's next well let's actually create our view so inside our cars let's create a new file create.blade.php now let's write down cars let's actually drag our index inside cars as well let's move it let's change our index view to cars.index and let's change the endpoint as well so inside the web.php let's change this to forward slash cars all right save it let's hop to google chrome i change the endpoints to forward slash cars all cars are printed out let's add a forward slash create after it and we have cars printed out on the screen what's next what we want to do is to add a create button somewhere here let's say right here first we need to hop to our index page again let's scroll up and let's go right below our class margin auto with eighty percent and padding on the y axis let's create a new div give it a class of padding top ten let's create an entry in here with the text add a new car and i want a symbol of at war let's change the href to cars forward slash create and let's give our button a class so let's say class is equal to border b2 padding bottom is two border dash dotted italic text dash create 500 save it refresh the browser and we have a button right here to add a new car if we click on it you can see that our endpoints change to cars forward slash create so what do we need to do when i create well we could basically copy everything inside of our index and paste it right inside of the create we don't need the car information so let's get rid of that and we don't need the button but we just need the content all right so inside the content let's create a new div which has a class of margin dash auto the width is again 80 percent and the padding on the y-axis is 24. this is the diff around everything so let's create another one with a class text center and in there i want an h1 create car the class is text 5 xl uppercase bold save it refresh the page now let's create our form by saying diff the class is flex justify items in the center justify in the center and the padding top is 20. now we need a form because we need to submit it and i'll come back later on the action and the method all right we have a div in here which has a class of block type is equal to text let me actually outline this on the line below the type it has a class of block shadow dash 5 xl margin bottom is 10 p 2 width is 80 italic and i want to add a placeholder but i want to style the placeholder so placeholder dash gray dash 400 let's give it a name of name and let's give it a placeholder so let's say brand name let's save it and test the output all right this looks fine let's copy paste our input actually so the second one has a type of text the class is alright the name is founded and the placeholder is founded we need one more because we have our description the name is description as well we need to submit it so we need a button so let's say button with a class of bg dash green test 500 block shadow dash 5 excel margin bottoms 10 padding overall is 2 and the width 80 uppercase and let's change the font to board and let's add a text of submit we need to submit our button so let's set the type equal to submit as well save it let's test the output and this looks alright we don't need anything fancy what's left here well let's scroll up because we need to change some things inside of our form whenever your user fills in the form the action is forward slash cars and we know that we're performing a post request so let's say the method equal to post if we fill in the form right now so let's say tesla 2000 test submit it's not working and this is related to cross site request forgery by default all laravel routes accept read-only routes so the get head or options request now if we go right below our form write down add csrf save it let's go back to chrome refresh the page and let's inspect the page for a second if we open our form you can see that we have an input type hidden the name is underscore token and the value is a weird id this token is generated at the start of every session and every non-read only route compares the submitted token against the session token so why do we do this it's mostly used when one website presents to be another the goal is for someone to hijack your user's access to your website by submitting forms from their website to your site let's go back to visual studio code let's go to our cards controller because we're ready to do something so we're creating a form but we want to store data so we need to work in our store right now and usually when i program i always perform a dd to see if my form will be submitted or not so let's say okay save it go back to chrome refresh the page click on submit and let me close off my inspect element and you can see that it actually works because ok has been printed out there are two ways how we could insert a record let me remove my dd the first one is by creating a new instance so let's say variable car is equal to new car what i just showed you then we could say that we have our car but we want to specifically say that our name is equal to the request method right here and from the request we could wrap http information from input and then the name of our input field so in our case it's name let's do the same thing for the column founded and description so car founded is equal to request look for input fields with a name of founded let's do the same thing for the description let's set that equal to request find an input field with the name of description let's save it let's go back to google chrome well let's change the end point to cars let's add a new car let's say it's tesla founded in 2000 and the description is test let's submit the form it actually works because we're not getting an error so let's hop to i term let's say select all from cars and well something went wrong right here because tesla has not been added inside our table and the reason why this did not work out is because we need to save it and that's not what we're actually doing let's say that we have our car instance and we want to perform the safe method on it so it will save the name founded and the description until you use this save method the instance of car represents the car fully but the data hasn't been saved before we test it out let's actually return a redirect to forward slash cars let's test it out let's go to google chrome refresh the page and you can see that tesla has been printed out and inserted inside our database let's test out an item let's select everything from cars again and you can see that tesla has been added all right the second way is the way that i actually prefer to use and that's by passing in an array to a model so let's actually comment out everything that we just created and let's create a new variable car and i set it equal to car and that's called the create method so what we need to do is to pass it in as an array so brackets and inside the brackets we need to pass an associative array so we basically need to do the same thing as we did before let's define our column name so name and i set it equal to request grab everything from input with the name of name comma found it grab everything from the http that's inside an input field with a name i found it now let's do the same thing for the description so request its input description this won't work right now because every time you want to pass an array to a new model every property that we have right here needs to be approved for mass assignment in our model file so what we need to do is to open our car model and right below our primary key we need to create a new property so protected fillable and let's set it equal to an array where we need to say which items can be mass assigned or columns excuse me so let's say the column name found it description let's save it let's hop back to google chrome let's create a new car let's say volkswagen i don't know when it is found and the description is volkswagen as well let's submit it scroll down and volkswagen has been added inside their database i need to mention one more thing in our cars controller we could use make instead of create as well but i prefer to use create because it will save the instance to the database as soon as it's called so we don't need to add the variable car save method and whenever you use make you actually do need to use it so that's why i prefer to use create this was easy wasn't it well well updating records are pretty similar you can get a specific instance change its properties and then save it or you could pass in an array of updated properties so right here we're going to work with the edit and the update page we're going to work with the edit and update method so same thing as before let's return a view in the edit form let's return our view for the edit form so return a view called cars dot create that's created so in our cars folder create a new file edit.played.php and we could basically copy paste our entire create file and the only difference is that we just want to add values in our input so let's copy it let's go to the edit page paste it right there but before we start editing something in our edit page let's quickly add an answer on every item that comes from the database in order to show the page so let's go to our index right insider for each loop and below our margin audio div let's create a new div let's give it a class of float to the right and let's create an entry in here and point to cars forward slash and we want to edit a specific post so we need to grab the id that we have from our car that we're printing out so let's say car id forward slash edit and just to make sure that our url is good let's go to item let me open a new tab now let me say php artisan route list now let's search for the edit action which is right here and you can see that it has cars forward slash car so the id forward slash edit all right let's add text first of edit and let's say and rar again let's give it a class of well we could actually copy the class that we have right here let's paste it in but let's change the text gray to text green save it let's go to google chrome refresh it and you can see that every item has a edit button let's click on it and you can see that the endpoint is good so we need to work on our form so let's do that let's go to visual studio code edit page let's scroll up let's say update the car and since we want to edit a specific row in our database we need to pass in that row to our views so let's hop to the controller again what we could do is to say dd variable id refresh it and the id is one which is right so based on that id we could basically say we have variable car let's set it equal to car and find me a car with that specific id let's do the car again save it refresh the browser now let's open attributes and we have a car with id number one the problem that we face right now is that the find method will return a collection so we need to loop over it and if we add the first method to it at the end so first we will return an object so we don't need to loop over it in our ui let me get rid of the dump and let's return it to the view and we don't want to pass it in as an array like i just said so let's say with cars as car well let's say car s car let's actually replace our view with edit let's save it let's go to chrome let's go back to the beginning let's click on edit and we're on our update and you can see that audi has been printed out let's do the same thing for the founded let's say value is car founded and for the description as well so let's say value variable car founded all right let's have a look at our endpoint because it's cars forward slash update right now let's hop to i-term and as you can see it should be cars forward slash the id so let's change that let's set it equal to cars let's remove update forward slash car id let's save it let's test it out in the output all right let's refresh it you can see audi the value over founded and the description so let's up to vs code because we're ready to perform our update method right now and we're basically going to follow the same approach so what we did in our edit was finding our car and we sent that back to the view so what we need to do right now is to basically go up copy the create method that we have scroll down paste it right inside of our update and we need to change a couple things right here we don't want to create but we want to update a car but in order to update a car we need to do something with this specific id that we have so the current post let's go right after our model let's say where pointer let's go on the line below and in our where clause let's see where the id is equal to the current id that we have right there all right are we done well no let's return the view as well so the redirect all right let's save it we're trying to update something right and that isn't possible with a post request as you could see right here our method is equal to post and in order to fix this in laravel we need to perform a put request which our csrf token will understand so let's save everything let's go to chrome let's change the name to aud2 and let's submit it something is going wrong right now with our token right or with our method and if you're familiar with html and php you know that it's only possible to submit a get or a post request so how do we fix this we could keep our method equal to post and we could go right below our token and say add method and we're basically want to transform our post request to a put request and that's how you use eloquence update model save it let's go back to google chrome well let's go back to our cars let's click on edit change rd to rd2 submit it and you can see that our name has been changed to rd2 now there's one more request left and that's the delete method that we have right below our let's see update method and once again the leading is very similar to updating with eloquent so first we need to create a form in our index.blade.php say right below our edit and it can't be an answer because we need the request and that's not possible when you create an answer so inside our form let's create our csrf token again our action is to forward slash cars forward slash the specific car id let's save it and let's go to i term as you could see right here destroying has a uri of cars forward slash the id the method is equal to post let me close it off actually all right and right below our csrf token we need to create a method where we want to delete so inside our form i want a button where the type is equal to submit and let's actually copy the entire class that we have of our answer above let's paste it right inside of our button and instead of saying green let's say red and let the text be delete delete with the same icon that we have save it let's hop to google chrome refresh the page and we have a delete button right here but let's add a little bit padding in our form so let's say class is equal to pt3 save it refresh it and this looks alright let's go to visual studio code we already have our id passed in right here so let's test it out let's say ddd that specific id save it google chrome refresh the page let's click on delete and the id is 1 which is equal to the uri let's go back since we already have the id inside our method we could go up to our edit copy the find method place it right inside of our destroy so we want to find where that specific id exists and we don't need to do the same thing as we did before with our creator update we only need to say car delete that specific row let's return a redirect to forward slash cars save it go to chrome refresh the page let's click on delete and you can see that it has been deleted let's delete them all and you can see that this works fine but to be honest this is not the way that i prefer what i usually like to do is to pass my model right inside of my method so let's get rid of id let's say our model car variable car and if we do this we don't need to pass in the id since it's already passed in inside our action so let's get rid of this line we do need our car delete because we can do it instantly and this is how you save yourself an extra line of code there's no reason to look up an instance just to delete it but this is a thing that i will show you later on as we proceed with the course i didn't change it at first because i thought it was just as easy to keep the resource list and we can do the same thing for other methods as well like i said that's not for now if you do like my content and you want to see more leave this video a thumbs up and if you're new to this channel please hit that subscribe button
Info
Channel: Code With Dary
Views: 19,560
Rating: undefined out of 5
Keywords: laravel, laravel 8, laravel php framework tutorial - full course for beginners 2020, laravel 8 tutorial for beginners, laravel php framework tutorial full course for beginners, learn laravel for beginners, learn laravel step by step, laravel full course, php laravel youtube, laravel tutorial youtube, how to learn laravel, laravel tutorial 2020 - the complete developer course, laravel tutorials from scratch to advanced, eloquent laravel 8, how to use eloquent in laravel 8
Id: ufCAN-bAFn0
Channel Id: undefined
Length: 45min 20sec (2720 seconds)
Published: Wed Dec 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.