Laravel Tutorial For Beginners (Simple User CRUD App)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey if you're watching this video you're interested in learning about laravel that's awesome laravel is the best framework I've ever used and it has so many amazing features but sometimes when you're just starting out and learning something brand new all of those features can be intimidating and overwhelming and it feels like a lot of tutorials out there try to teach you a hundred different features and 500 best practices and tips and tricks spread out across 400 different files when really you're just looking for a beginner's tutorial to keep it simple anyways learning about all of those features and best practices that's fine in a 20 hour video course but in an intro Youtube video like this you don't need to learn every best practice and cool feature that exists in a framework in a video like this you're probably just trying to wrap your mind around what laravel is and how to genuinely understand the very Basics and get started right with a really minimalist example app so my goal is not that you'll be a laravel guru by the end of this video but simply that you'll have a bird's eye view of how laravel works at the most basic basic level and that it will actually make sense to you now before we get started with the action let me show you a sneak peek preview of the finished product of what you and I are going to build together in this video so when you first visit the home page you have two options you can sign up for an account or you can log into an existing account let me just go ahead and log in with an existing account really quick once you're logged in you know it says welcome and then your name you can click log out we don't need to do that right now you can create a brand new post so I'll say like post for example video here is my content I can go ahead and create the post and then down at the bottom we see my posts and it's just going to list all of the different posts you've created now for each post you can edit them so if I click edit you know if I want to add exclamations to the content click save changes there you see it or if I want to delete this post entirely I can click delete and now it's gone cool and now as far as features that we can't visually see right now we'll also set things up so that you only have permission to edit and delete your own posts right you can't just go around deleting other people's posts cool now I should also be clear that this video is not an installation or Dev environment setup tutorial I've already posted a different video on my YouTube channel that shows you how to get PHP and composer installed and ready on your computer so you can find a link to this video in the description for the video you're watching right now but essentially by the end of this video we have everything we need and we actually learn how to set up a brand new empty laravel project from the command line so the video you're watching right now assumes that you have that ready to go and that you know how to do that if you don't know how to do that that's okay you can go watch this video first so long story short the video you're watching right now is not about setting up a Dev environment this video is about actually understanding laravel so at this point we are ready to get started here's what we're going to do on my desktop I have a brand new folder it's completely empty and I just named it YouTube demo you could name your folder whatever you want but let's go ahead and open up that folder in vs code so here it is it's completely empty I'm going to jump into the command line and with the command line pointing towards that folder we're going to say composer create Dash project and then it's laravel slash laravel and then a space and a DOT to just say hey we want to install this in the current directory that we're in right now let's go ahead and press enter this should only take maybe 30 seconds but it will be very quick you can see that that's going to automatically generate all of the files and folders that we need now as soon as that finishes you can go ahead and say PHP Artisan serve go ahead and press enter and now with that up and running it's just going to continue to run until you tell it to stop so with it running in your browser you can visit localhost colon 8000 so you're going to see a page that looks something like this this is you know the default laravel starter screen for a first step I think it's always empowering to just make a quick edit to the page we're already looking at right here so to do that back in vs code just go into the resources folder and then the views folder jump into welcome.blade.php so for example if I just search for the word wonderful you know the text that says laravel has wonderful blah blah blah maybe I'll make it so that sentence ends with a bunch of exclamations instead of a period And if you refresh there you see the exclamations cool so we can edit that template but what if we wanted to create our own brand new template so do this with me in that same views folder let's create a brand new file it's a new file you could literally name it anything but why don't we name it like home and then dot blade dot PHP so the home portion of the name could be anything but then it does need to end with DOT blade.php cool now in this file let's get a starter template so you can type Doc and vs code and hit tab in the body area let's just say you know heading level one testing one two three let's go ahead and save that file and now if you refresh obviously laravel doesn't know to do anything with that new file we just created so here's what we're going to do go into your routes folder and jump into the file named web.php you're going to be spending a lot of time in this file this file essentially spells out what should happen for all of the different URL patterns on your website so when you send a get request to the base URL you know like the home of the domain just slash it's going to return that blade template or that view the file that was named welcome.blade.php so we could change this from welcome we named our file home.blade.php you don't need the dot blade just the starting part of the name if you save that now if you refresh perfect if you wanted to you could go ahead and delete the welcome.blade.php file cool so at this point let's jump into our home.blade file and instead of this heading level one let's set up a user registration area now this video is absolutely not about CSS or SAS or bootstrap or Tailwind or emotion so we're not going to worry at all about CSS or styling so I'm literally just going to create a div and you know you would never do this in the real world but I'm going to give it you know style equals border 3 pixels solid black in this box so this will be like the user registration area so we can have maybe like a heading level two that says register and then we could have a form for now we can leave the action to blank but in the form let's have you know an input let's say placeholder equals uh name and then let's have another input and placeholder equals email and then finally an input and placeholder equals password for password you can change the type to password instead of text and then finally still in the form tag though let's have a button that says you know register so you can save that if we refresh cool so that was just basic HTML this had nothing to do with laravel now the question is how do we actually tie this into a laravel application like how would we actually let the user register for an account sign them up into a database generate a session so on and so forth well let's not get too many steps ahead of ourselves let's take this one step at a time so before we worry about the database or sessions let's first just learn how to submit an access form data in laravel so to do that back in our HTML on the opening form tag let's fill in the action right and that's the URL that this form is going to submit to so let's say slash and I'm just making this up but like slash register for the URL let's add an attribute of method and put that to post at this point we can go ahead and save this file and now let's jump back into our web.php file right this is the file that lives in the routes folder this is what says what should happen for all of the different URL patterns on our website so this is the Baseline route right below that let's say you know uppercase route colon colon when someone sends a post request to and then in these parentheses we're going to give it two arguments so the first argument is just the URL pattern so quotes you know slash register that's what we're looking out for the second argument is a function that you want to run you know at the appropriate time so let's spell out an anonymous function so function parentheses curly brackets and let's just return you know a string of text that says thank you semicolon give that a save so if you submit this form right it doesn't matter what you put in the data you could actually just leave it blank but if you click register aha I'm glad we ran into this error together so essentially anytime you send a post request in laravel in order for it to actually go through you need to include a csrf token explaining what csrf means is outside the scope of this video essentially it just means that we're protecting the visitors of our site from having third-party sites take advantage of their logged in cookie data from our good innocent site the good news is that laravel makes it really easy to implement and you don't need to understand csrf in order to be protected however if you do want to learn a little bit more about cookies and you know csrf attacks in general I've already created another video on my YouTube channel so here it is you can just search for you know my name and then here's the title of the video and that has all sorts of good info anyways back to the task at hand how do we get around this error message simple go back into your HTML so our blade file and right inside the opening form tag let's just say at symbol csrf now obviously this wouldn't do anything in plain HTML but because we are within a blade template file we have access to this at symbol and then we can call different utilities and tools like this so if we save that and then if I refresh and just submit the form again beautiful we see thank you now we don't want to literally just respond with the words thank you we would want to you know look at the data that they actually submitted in the form now before we get to that I do want to include one little bit about staying organized so back in our router file in web.php we've seen that yes you can include an inline or Anonymous function here for a route clearly that's what we're already doing but in order to stay organized it's much more common to include these functions in a totally separate file and that separate file that I'm referring to would be called a controller so the idea is that you can split up the functionality of your application into different controllers like we'll have a user controller and then we can have a blog post controller so on and so forth but the idea is that you're tucking away those functions into those separate controllers instead of this web routes file becoming bloated you know with hundreds or thousands of lines of code so let me show you what I want to do right now let's essentially split this function into its own file so this has to do with registering a user so why don't we create a user controller let me show you where controllers live so in the app folder and then in the HTTP folder and then in the controllers folder we only have this default controller.php but in this folder we want a new file so check this out in the command line you can go ahead and open up a second terminal so leave this one running the PHP Artisan serve but open up a secondary terminal and type this in with me PHP artisan make colon controller and then we just make up the name let's call it user controller there is nothing special about this name I'm just making it up go ahead and press enter and you'll see that in the controllers folder we now have this brand new file usercontroller.php let's jump into that file and check this out down here in the class we see this comment let's create a brand new function so let's say public function you could give it any name you want I'm literally making this up but why don't we call it register I think that's a you know a fitting name here so parentheses curly brackets and literally just return a string of text that says hello from our controller so my colon give that a save now here's what we're going to do back in our routes file the web.php file let's use that function here for the slash register page or I should say URL so for this second argument get rid of this inline function right so now it's just you know our first argument comma we'd be ready for a second argument here's what we're going to do give it an array so square brackets in that array we're going to give it two items so the first item is our controller class so we're just going to say user controller colon colon class the second argument or not an argument I should say the second item is in this array is the name of the method on that class so we just made up a name of register now before we can save this file and expect it to work we do need to import or load or you know require in our user controller now there's a 99 chance you don't have the same exact vs code extensions that I have installed so you can ignore this step but I'll explain how it makes sense in about 10 seconds from now but if I just right click on user controller and click import class that automatically added this line at the top of the file for me now you don't have that ability to right click but what I want you to I'll show you how to get it in just a minute but what I want you to do is just pause the video and type this in at the top of your web.php file and do know that these are backslashes not forward slashes go ahead and save this file now before we test this out I want to show you how you can also have access to just right click on something and choose import class essentially in vs code click on this extensions item in the left hand menu and then you just need to search for this item or at this extension it's called PHP namespace resolver as soon as you have that installed you'll be good to go and then you can right click on things just like I do and click import class also just another tip to improve your blade support in vs code I really recommend this extension as well it's called laravel blade Snippets cool anyways at this point let's go ahead and save the web.php file and now let's test it out so if I go back and submit the form again perfect hello from our controller so this means that we're successfully leveraging this function in our controller now we don't actually just want to say hello from our controller let's actually start to do something useful here's what we're going to do let's try to access the data that the user types into these fields so back in our controller within the parentheses for our function of register let's include a parameter in the parentheses we're going to say uppercase request and then dollar sign request so what this means is we're filling in the metaphor for what a request is with the incoming data you know that the user actually typed into these fields now we're able to use uppercase request like this because we've already imported it or I should say the boilerplate code that laravel created for us is already importing it here So within the body of our function before the return line let's say this dollar sign let's make up a variable we could name it anything we want but I'm going to call it incoming Fields equals and then we can leverage you know dollar sign requests so dollar sign request look inside it for a method of validate now in these parentheses we're going to spell out an array so square brackets and then I like to drop down and I'm just going to say that all three of the fields are required if you leave one of them blank I don't even want to move on I don't want to proceed any further I'm essentially just going to reject your request and you're going to get redirected back to this form so in the array I'm just going to say you know name should be required comma I'm going to say email should be required comma I'm going to say password should be required so if this validation fails laravel will take care of things for us it won't even move past this line so the user would never even get to see Hello from our controller we can test this out so if you save that and then for example like if I leave my name blank but I fill in these other two Fields I click register see it just kicks me right back I don't even get to see that string of text message but if I do fill out all of the fields if the validation passes whoops you can see it still fails and that's simply because we forgot to name these inputs in our HTML so let me show you how to fix that back in our blade template on these inputs you would just need to give them matching names so like name equals you know name or the username this one would be name equals email and this one would be name equals password this has nothing to do with laravel this is just a standard with any back-end server just HTML forms and servers in general right these will be available on the post body data that the browser sends over and it's required that you you name them cool so if you save that and then you refresh if I leave one of the fields blank you see it kicks me right back but if I do indeed fill all three Fields out and click register perfect hello from our controller now before we move on let's set up more specific validation so back in our controller for the name or username field instead of just quotes with required you can actually give this an array so square brackets and you can spell out multiple rules that must be met so like quotes required but then comma quotes you could say like Min colon 3 it needs to be at least three characters you could say comma you know quotes Max colon 10. let's do the same thing for email so instead of just required let's actually give it an array so the first item is required but then comma it must be in the email format right so like a string of text and then the at symbol and another string of text for password let's do the same thing so an array yes it's required but also let's give it a minimum length of let's say like your password needs to be at least eight characters long comma and let's say a maximum can be 200 characters long cool so you can save that and we can test it out so like if I choose a username that's only two letters long click register you can see it kicks me back now don't worry in a real project you would learn how to have validation messages that would appear next to this specific field that's having a problem but again we're not worried about learning every single feature and every best practice in laravel that would be a 20 to 30 hour course let's just keep things really basic in this quick video anyways if I choose a username that's three characters long and I type in a value that looks like an email address and I choose a password that's at least eight characters long then we are successful perfect so we've learned how to validate the data in just a minute I can show you how to access those values that the users typed in but before we get to that let's realize that we would want to store those values in a database somewhere so I'm going to assume that you already have MySQL installed on your computer if you don't that's okay there are already 50 billion tutorials on the internet and on YouTube on how to get MySQL installed on your computer right this video is about making sense of laravel not installing MySQL but anyways on your system let's just create a brand new mySQL database so I'm going to create a schema I'll just name it you know YouTube demo go ahead and click apply cool so now I have this brand new database it doesn't have any tables in it yet but let's go ahead and connect our laravel project to this mySQL database so here's how we do that in vs code you're just going to look for your file that's named dot EnV around line 11 you'll see the details related to your database so for me the database name I just chose it right YouTube demo you'd have to choose in you know value that makes sense for you my local Dev username is just root and the password is the super secure root root cool go ahead and save that file and now before we actually tie in our user controller to the database we first want to make sure that our database has some of the basic tables that laravel will set up for us to do that we're just going to run a command so in the command line just type this in with me PHP Artisan migrate go ahead and press enter and what that's going to do if you go back into your database and refresh you now have several tables so laravel will create these for you failed jobs migrations password resets personal access tokens and aha the most important one users so if I look at that table right it's got ID name email password so on and so forth so what we want to do now is just take whatever values the user types into these fields and actually create a row in this user's table here's how we do that back in our user controller before we return you know hello from our controller but after we're validating things we would just want to create a new instance of our user model now we haven't discussed what a model is but big picture a model is like a metaphor or a way of mentally mapping out the data for an item so you're going to have a model for a user you're going to have a model for a blog post you might have a model for like blog post comments right but a model is just sort of mapping out uh the data structure the relationships for a piece of data Now by default laravel already has a user model for us so it's uppercase user colon colon we're going to use its create method semicolon in these parentheses we give it our dollar sign incoming Fields right this is the data whatever the user actually typed into these fields that we would want to fill in the metaphor for what a user is with now before we actually go save and test this out before that line let's be sure to Hash the user's password we would never want to store the user's actual simple plain text password in a database that is just about the worst thing you could do so here's what we're going to do right above this user create line let's say dollar sign incoming Fields look inside that array so square brackets for the password item and then we're just going to say that that equals and then laravel has access to the bcrypt function we don't need to import it we just have it available as a global utility function so in these parentheses just give it the plain text password so that it can hash it so that's dollar sign incoming Fields look in the array for quotes you know password cool now before we save this we also need to right click on uppercase user and click import class and then up here that's going to give you a choice we want this one that's app models user so if I click that you can see it automatically added this line for me cool let's go ahead and save this and test it out so back in the browser Let me refresh and actually choose values that I want so I filled those in let me click register hello from our controller but here's the cool part if you go into your database and refresh the view for that table beautiful stored all my data and most importantly it hashed my password right clearly that is not the value I actually typed in as my password so now if your database ever got leaked you wouldn't be revealing the passwords for all of your users cool so now that we've learned how to store a user in the database though now let's think about the concept of having a user be logged in right you should be able to log in and log out that involves sessions and cookies now currently we just successfully registered but we're not actually logged in so let's go back to the home page and let me show you what we can do so that when you register you just get automatically logged in so first of all on this line where we're saying uppercase user colon colon create this is going to return an instance of a user and we don't want it just floating in outer space we want to sort of hold on to it so at the start of this line I'm going to make up variable you could call it anything I'm just going to call it you know lowercase user equals whatever this is going to return cool so we've held on to this now on a new line we can say call the globally available auth utility function and then look inside it for the login method now which user do we want to log in you guessed it this user that was just created so dollar sign user finally instead of returning a string of text let's just redirect them back to the home page URL so you can just say return redirect send my colon where do you want to redirect them to quotes just the home page base URL before we save this let's add a detail where the username and the email must be unique right so laravel can look in the database and make sure that no other you know users have those items or the I should say that value so for name just add one more item in this array so comma and then uppercase rule colon colon unique and then we're just saying on the users table comma the name field needs to be unique in order for this to work we do need to right click on uppercase Rule and click import class and we want this one illuminate validation rule cool and then I would do the same thing for the email address so comma you know rule colon colon unique on the users table the email field must be unique cool let's go ahead and save this and now to really test that you're logged in let's go adjust the home page blade template that we're going to redirect the user back to once they register in law are logged in let me show you what I have in mind so back in home.blade.php right up at the top right below the body tag let's say at symbol auth and then you know have a blank line and then say at symbol else and then at symbol end auth so the idea is whatever we include here will be shown if the user is logged in right with a cookie in a session otherwise else show them this so what I'm going to do is just cut and paste this div for the registration form just cut that to live inside this else area right here but if you are logged in let's just have a paragraph that says uh congrats you are logged in cool so if you save that and you refresh right obviously we're not logged in at the moment so we see this registration form go ahead and register though so I filled out the forms with the username of Brad 2 let me go ahead and register cool it redirected me back to the home page URL and there we see congrats you are logged in so in Google Chrome I'm logged in but here's a different window this is Mozilla Firefox and if I visit localhost colon 8000 you can see I'm not logged in so on that exact same URL I see the registration form let's go ahead and set things up so that when you are logged in there's a button that lets you log out so here's how I would set that up maybe right below that paragraph in this auth section I would just have a form for the action let's send the URL to you know slash log out let's say the method is post in the form literally all we need are two things we need the csrf token and then we need a button that gets clicked on so let's just have a button it says log out cool let's go ahead and save that and now we need to go create a route for this URL pattern of Slash logout so go into your web.php file down at the very bottom let's say you know route colon colon post we know that we give this two arguments right so this is the first one then the second one so the first argument is the URL pattern so slash log out the second one is an array this is how you point towards a method on a controller so we're going to say user controller colon colon class comma and we can add a method on the controller we can name it anything we want but I'm going to name it log out so save that then go into your user controller and now on our class we have the one public function named register right above or below that but inside the class let's just create another public function this time we're going to give it a name we're making it up log out in the body of this function we're just going to call the globally available auth function and look inside it and call the log out method then we're just going to redirect back to the home page URL so return and redirect I've just slashed semicolon give that a save so in this window I'm logged in if I refresh now I can click log out as soon as I click it awesome cool so our registration form works you can log out now on this guest screen we need to have a form where you can log in to an existing account so first of all let's add the HTML form that would let you log in so back in home.blade.php down in the else area I'm just going to duplicate this div that has uh you know the border around it just duplicate it on the new copy let's change the heading level 2 to say log in and then let's change the action URL to be slash login cool we do not need the email field so we can delete that and let's actually change the name of this field so let's call it like login name and then let's change the password to be for the name value login password that way we don't have two of the same field with with the same name on the same page cool and then on this button let's have that say login instead of register cool so if you save that you get the idea now how do we make this form come to life well it's going to submit to this URL of Slash login so you already know what to do we're going to go into our routesweb.php file and you can literally just duplicate this line for the log out route just duplicate it change the url pattern to slash login and the method on the user controller would simply be login instead of log out so we can save that then jump into your user controller and right above this function let's just create a public function with the name of login now we do need to access the value that the user types into these fields so here's what we're going to do in the login function parentheses here let's fill in the metaphor for a request with dollar sign request in the body of the function I'm going to begin by creating a variable you can name it anything but incoming Fields equals dollar sign request call its validate method give it an array I'm just going to say that both login name is required and login password is required if you don't include both of those I'm not even going to bother attempting to log you in assuming you do have those then let's actually attempt a login so if parentheses currently brackets below the if block whether the login attempt is successful or it fails we're going to want to return a redirect back to the home page but for the if condition we're trying to see if the username and password they supplied is a match is there actually a user in the database with that matching username and password so here's what you do for the if Condition it's called the auth function look inside it for its attempt method in the attempt method you're going to give it an array we're going to give it two things the name that they're trying to log in with and the password value they're trying to log in with so we'd spell out an associative array so name would be dollar sign incoming fields look in that array for and we named it log in name in between the two closing curly brackets comma you're also going to give it a password so call in or excuse me quotes password building out an associative array this would be dollar sign incoming Fields look in the array for login password cool so now only if that is successful then we do want to generate a session and a cookie and you know consider this user logged in so to do that we would just say dollar sign request look inside it and call the session method look inside that and call the regenerate method give this a save and let's test it out so let's fail the login attempt on purpose so if I just type in values that obviously are false it just redirects me back to the home page and nothing changes however if I log in with correct values so Brad 2 and the password I just chose I log in awesome congrats you are logged in it's still the same homepage URL but now we're seeing the content that only logged in users can see and as soon as we click log out perfect really quick let me log right back in So now that we have this interface where logged in users can visit let's go ahead and set up the ability for them to create blog posts now if we look at our database you'll see that yes laravel has preconceived notions right out of the box of what a user is right has a user's table a user model the shape of the data right it already had its own opinion that they should have a name an email a password so laravel already knows what a user is out of the box but laravel has no idea what a blog post is or really Beyond a user laravel doesn't know what anything is so for any other type of data on your site you need to spell out the shape of the data like instead of blog posts if you think you know your website was like a pet adoption agency you'd have a table named pets and the shape of the data would be like the name of the pet the species of the pet the fur color of the pet the favorite food of the pet so on and so forth now before you just start manually creating a new table uh you know called posts and setting like a title column and a body content column don't do that in laravel there's a much more organized and easily repeatable and replayable process of creating database tables let me show you how laravel handles this is really cool it's all automated so in the file explorer if you look not an app but in a database you'll see that there's a folder called migrations now laravel ships with these migrations by default out of the box so it's going to create a user's table you know these different default tables however you and I can create our own brand new migration file right now so what we're going to do is say hey laravel we want there to be a new table called posts right for blog posts but you and I don't have to create the table ourselves laravel will do it for us so how do we create a new migration file simple go ahead and open up your command line and run this with me we're going to say PHP artisan make colon migration and then we just give it a name what's really cool is if you follow a specific naming format laravel can sort of read your mind as to what you're trying to accomplish so if we name it create underscore posts underscore table go ahead and press enter you're going to notice that now in the database migrations folder there's a brand new file with today's date called create post table and if you open up that file beautiful in its up function you can see it's going to create a table with this exact name of posts and then if you roll back the migration it's going to drop that table now in this up function this is where we spell out the shape of the data so in addition to the ID column in you know the timestamps column so that's going to give us like ID and then the date that the item was created at for example in addition to that we would want to spell out other fields like that's the title of a blog post and also the body content of a blog post so maybe right below this line where it says table timestamps I'm going to say dollar sign table look inside it and I'm going to call the string method and give it a name of title cool then let's say dollar sign table look inside it and call the long text method and give it a name of body right for the body content and then finally each blog post should keep track of which user authored it like who's the author who created the post so finally we'll say table look inside it call the foreign ID method at the end of that look inside it and call a method of constrained so what this is going to do is laravel is not even going to let the operation go through when you create a blog post if this matching ID does not actually match a real user in your database so the name for this foreign ID that would Point towards a user would just be quotes user underscore ID we'll see where this comes into play in just a moment but at this point I want you to save this file okay and now you won't see a new table magically appear in my sequel we do need to run a command so here's what we're going to do we're going to run a command of PHP Artisan migrate so what this is going to do is it's going to run any migrations that have not yet been Ran So if we push enter it's just going to run our one migration that we just created and now if you refresh your mySQL database you'll see a brand new table named posts and if you look at the shape of the data beautiful we've got ID but most importantly title and body and the user or the author the person who created the post now that we have this database aspect taken care of let's go back to the HTML side of things and when you're logged in let's have a form that says create new post and it lets you type in you know a title and body content so back in our home.blade.php up towards the top this is the content you'll see if you're logged in so for example right below the form but before the else let's just have a div with a border so I'm just going to borrow this copy and paste it and then let's have a closing div and let's have a heading level two that says create a new post and then let's have a form the action let's have the URL submit to slash create Dash post and Method will be post in the form so let's drop down we want to begin by saying at symbol csrf and then let's just have an input for the title value so input hit tab text yes but let's give it a name of oops title okay then let's have a text area for the body content so the name would be body we don't need ID columns or rows and then you could add placeholder values so on the title you could say you know placeholder equals title post title whatever you want to put here and then on the text area you can say placeholder equals you know like body content dot dot dot cool finally below the text area let's have a button that just says you know save post or create new posts whatever you want to have let's go ahead and save this and now before we even submit the form we would need to pay attention to what should happen when you send a post request to this URL pattern so let's go back into our routes file right the web.php file and so far it's just been leveraging Anonymous functions or functions or methods that live on the user controller at this point though let's stop and think about it so the user controller is for registering logging in logging out we should probably have a separate controller called a post controller that's for all blog post related tasks so and this is just to stay organized but here's what I'm going to do let's run a command of PHP artisan make colon controller be sure to spell controller correctly and I'm going to choose or make up a name of you know post controller go ahead and press enter and now that's going to create a new file in app HTTP controllers there it is postcontroller.php now if you're anything like me it's a bit slow and annoying to dig through a folder structure like that so if you're using vs code a way faster way of finding these new files like you know assume you just ran that command in your command line you can immediately find the file by pressing command p on Mac or control p on Windows and then just literally start searching for postcontroller.php it's going to be the first suggestion just hit enter beautiful okay in this post controller you know in the actual class let's get rid of the comment let's have a public function named well we can make up the name the name doesn't matter let's make up a name of create post parentheses curly brackets you don't even need to save this file because we're going to jump right back into it but let's go into our web.php file and down at the bottom let's spell out our blog post related routes now you can even have a comment if you wanted to right blog post related routes so you could say route calling colon when someone sends a post request to right we're going to give it two arguments the first is the URL pattern of Slash create Dash post and then the second argument is the function that we want to run in response so give it an array post controller colon colon class comma the second item in the array we named the method create and then we uppercase the p in post now before we save this you want to right click on your post controller here and click import class that automatically adds it up here cool let's save this file and then go back into your post controller now how do we actually access the values that users type into these fields simple in our function parentheses here we're just going to say you know fill in the metaphor of a request with dollar sign request and then in the body of our function I'm going to type really quickly because we've already done this in the user user registration and login process but I'm just going to make up a name incoming field set that to equal dollar sign request call its validate method give that an array I'm going to say that the title field is required I'm going to say that the body field is required okay next I don't want to let people store any sort of actual code in my database like HTML tags or any kind of malicious content so I'm going to strip the content before I actually save it into the database so I'm going to say dollar sign incoming fields look in the array for the title I'm going to set that to equal to and then call strip tags and then just feed it the in the original value so incoming Fields look in the array for title now to save typing I'm just going to duplicate that line and change title in both instances to body okay let's also fill in the user ID right if you look at the database the user ID this should match the ID of the user who's creating the blog post so if you look at your users table right has your name your email Let me refresh that right there's Brad and Brad too has their email addresses well each row you can see each user has a unique ID number so that number represents that unique row that user ID is what you would want to store as the user ID value on a blog post row so here's what I would do down here I would just say dollar sign incoming Fields click on the array for user underscore ID and set it to equal and then just call the global auth function look inside it for the ID method cool now at this point this array of properties incoming Fields it is ready to be saved into the database so I'm just going to say uppercase post for the Post model colon colon create right just like when we created a new user or registered user we said uppercase user colon colon create now in these parentheses you just feed it the data you want to save so dollar sign incoming Fields however before we save this file we have to realize that laravel doesn't have a built-in model for a post yes laravel had a built-in model for what a user is but we need to create the model ourselves for what a blog post is or you know if you had a pet adoption agency you would need a model called uppercase pet so how do we create a post model simple in your command line just say PHP artisan make colon model and now you don't want to just make up a name the name here matters so before we run this command if you look in the database right we chose the database table name of lowercase posts plural so to have this automatically be linked to our model we want to choose the singular uppercase version of this so if our database table is lowercase posts our model would be uppercase post just like this go ahead and press enter and let me show you what that just did in your app and then in your models folder you now have a file uppercase post.php so now that's what this code can reference uppercase post so now you could right click on uppercase post click import class beautiful below this line let's end things by just redirecting back to the home page so return redirect to the home page let's give this a save and now before it's going to work we do need to go into our post model so in the models folder go into post.php and let me explain what we want to do here actually if you go into your user.php file as a reference you'll notice that around line 20 laravel already included this for us on our user model so laravel was just saying hey when you're creating a new user record in the database these fields these can be Mass assigned you can assign these values all at once so that it's easy and convenient so we would just want to do this same thing for our blog post model so literally in our post.php model file right below this you know in the actual class I would just say protected dollar sign fillable equals an array and then I'm just going to spell out title body and user underscore ID semicolon give that a save cool now we might have missed one other tiny detail I don't know I'm just doing this off of memory let's find out if we run into an error we can fix it together so if I go back to the home page and I fill in you know say my first post here is my content and I click save post it redirects me back let's see if it actually worked though if we look in your mySQL database and refresh the post table beautiful my first post here's my content and because I'm logged in as the Brad 2 user you know my user ID is two so for example if I create another post uh another Brad 2 post hello and I saved that look in the database cool both of them have a user ID of the Brad 2 user if I log out and I create a Barks A Lot account I register and now I create like dog Post Number One and you go look in the database beautiful that new post has a user ID of three so now you can see we're already keeping track of this relationship between a user account and a blog post row or record so with that relationship between a user and a post in mind I think our next bit of business should be on this logged in homepage content area right about here let's display any and all posts that the logged in user has created now at this point I think the concept of what a model is is probably one of the cloudiest or most confusing Concepts we've covered in the video so far right what in the world actually is a model you know and we said that it's sort of a metaphor for a type of data but I think what we're about to do is going to make a model truly make sense so one of the most important features of a model is explaining the relationships that it has with other models so if we want to display any blog posts that the current logged in user has let's just go spell out the relationship between a user and a blog post in our user model file so check this out do this with me jump into your file that's named user.php to remind you that lives in app and then models and it's user.php now down at the bottom but still in the overall class uh but so inside this closing curly bracket but maybe just right below this protected line so right about here let's say public function and you can name it anything you want like oftentimes it would make sense to just name it posts but just to drive home to you that the name doesn't matter I'm going to name it like users cool posts parentheses curly brackets in the body of this function here's what we're going to return we're going to return a relationship between a user and any blog posts that they've created so return dollar sign this look inside it for the method of has many I'll explain this syntax in just a moment but in these parentheses we're going to give it two things the first is the class that you're trying to create a relationship with so it sort of reads like a sentence the file we're in is a user.php so we're saying that a user has many blog posts so what goes here just the blog post class uppercase post colon colon class now you might think that hey we need to right click on post and import it we actually don't because this is such a specific use case laravel can figure out where that model file lives anyways this second argument this is the field on this item in the database that spells out the relationship like what piece of data is actually powering this relationship and if you look on a blog post row it's this it's this column that's you know user underscore ID that's what's powering the relationship so quotes user underscore ID let's go ahead and save this and now let me show you how we can leverage users cool posts this new function to do that let's jump back into our web.php routes file because remember up at the top here for the home page URL we're actually not pointing towards a method on our user controller that's okay we can just spell out a function right here now actually in just a minute we can leverage that user's cool posts function on our user model but first let's just pretend that oops let me log back in really quick let's pretend that instead of showing the blog posts for the current logged in user imagine we just want to show all blog posts from all users because doing that is a little bit simpler and then we can move forward so it's really easy to load all blog posts from the database within our function we would just use our blog post model so uppercase post colon colon and then it has a method of all so my colon let me right click on post and import that class okay so this is going to return all blog posts but we don't want that just floating in outer space we want to pass that into our blade template so here's how you can pass data into your template the first argument is the name of the template you want but then you can give it a second argument and you just give it an array of data so let's spell out an associative array imagine we want the variable to be called posts and then this symbol for an associative array value and now you could just you know cut and paste this to live here or you could assign this to a temporary variable like this you could say you know dollar sign posts equals that and then you could just reference that here but the idea now is whatever name you chose here you can use this in your blade template so check this out we can save this and then back in home.blade.php maybe below the create new post div let's just recycle this to have a div right below that close that out uh The Heading level two can say all posts and now to Loop through a collection you would just say at symbol for each parentheses and then We're looping through our variable of posts as and then just make up a singular name so like there's nothing special about this I'm just making up you know post then we can say you know as symbol end for each but now in between those two lines we can Loop we can Loop through our collection here so for example let's have a div for each blog post and maybe I'll just give them a gray background so style but you know background color gray padding 10 pixels margin 10 pixels and then we can say you know H3 have the title so just double curly brackets to Output a bit of text in Blade and we just look inside our post for title and then maybe below that just have the body content so dollar sign post look inside the array for body so let's go ahead and save this and now if we refresh the home page cool so we see all blog posts from all users but what if we only wanted blog posts where the current logged in user is the author so I'm logged in as the Brad user I shouldn't be seeing this dog post by Barks A lot well there are several different ways we could set this up let me show you the first way that does not use our relationship because I think that'll make you appreciate how useful the relationship is so back in our code back in our web.php file instead of just using the All method on our post model we could say where and then where user ID comma is the ID of the logged in user so you can call auth look inside that call ID and then after we call where you want to be sure to call git now if we save that and I refresh perfect instead of seeing three posts now I just see the two that are actually by you know the logged in Brad user however even though this works this is missing the entire point in the entire power of setting up relationships because in this line of code we just wrote we're beginning our metaphorical sentence from the perspective of a blog post but why don't we instead begin the sentence from the perspective of our user model so check this out you could delete this line entirely I'm going to comment it out just so you can compare and contrast but let's say you know dollar sign posts equals and then let's use our user model now instead of using the user model as a whole let's actually use the current logged in user the instance of a user so you can just call auth and then call user that's going to return an instance of the user model the user that's currently logged in so if that's what we're working with that means we can now call you know back in our user model remember we named the function users cool posts that returns that relationship so we can just call users cool posts and then look inside that and call latest because we want to order them by the date right we want the newest blog post on top and then finally we'll call git so now if we save that and you will need to be logged in if you're not logged in you're going to get an error message when you refresh but now you can see we're only getting the blog post for the logged in user and they're ordered you know with the newest ones on top now to get around that error if you're not logged in here's what you could do you could begin by saying that posts equals just an empty array and then wrap this line and you can get rid of this line now the idea is just this one began from the perspective of a blog post this one is beginning from the perspective of a user so it feels a bit more intuitive right and we're not having to spell out the query parameters our relationship has already taken care of that for us but we could get rid of this line and then just wrap this line in an if statement so you could say like if the condition would just be if auth and then called the check method so only if you're logged in do we want to get blog posts for the current logged in user cool so I can refresh beautiful and in this window if I logged in as Barks A lot I actually spelled the name wrong as Barska lot but let me log in beautiful I only see the one blog post for the user that I am cool at this point let's go ahead and add edit and delete buttons for each blog post that you see when you're logged in so let's start with our blade template so in home.blade maybe below the body content I would just have a paragraph and inside it I would just have an a element so a link and the href value would be slash and I'm just making this up but let's say like edit Dash post and then this would be like the ID number of the specific blog post that you're trying to edit right we're just going to take them to a different screen where you can change the title and body content so to make that Dynamic I would just have you know double curly brackets and then I would just look for the current post for its ID value cool and then the text that you actually click on here can just say edit below that let's have a delete button now a delete request is a little bit different this is just going to perform a get request to a new URL for a delete request we're not going to send a get request we're probably going to send either a post or ideally we're going to send a delete request in other words in order to perform that kind of an action you need a csrf token so let's have a form so form let's make up a URL for the action let's send it to you know slash delete post slash and then the poster trying to delete double curly brackets dollar sign post look inside it for ID let's be sure to include method equals Post in just a minute we can learn how to actually send a delete request instead so check this out inside the form as always we can begin with our csrf token however laravel's has a really cool feature so normally with HTML forms you can only send git or post requests right but with JavaScript you can send asynchronous requests you can send delete requests or put requests well with laravel even though it's just a traditional HTML form we can actually say at symbol method and then just say delete cool let's also obviously have a button that says delete let's give this a save so now when you refresh each blog post has edit and delete functions now let's set something up so you can actually use these buttons so let's begin with the edit button right currently when you click it it's going to take you to slash edit post and then the ID for that blog post so we need to set up a URL pattern that's watching out for this so you know what to do just go into your web.php file we have you know blog posts related routes let's just set up a brand new one so when you send a get request to slash edit post slash and then curly brackets this is how you set up a URL variable and let's just say post so the idea though you know this is going to be a number like one two three okay then comma an array post controller colon colon class comma let's have a method name of like uh show edit screen give that a save and now let's go on to our post controller and create a method with that name so in post controller up here I just say you know public function I named it show edit screen parentheses created brackets now here's the cool part in these parentheses we can fill in the metaphor of what a post is with the incoming post variable in the URL pattern now here's what's really cool about laravel if the name you choose here matches the name you chose for your you know the dynamic part of your url laravel is going to perform the database lookup automatically for us so now in the body of our function we didn't even do anything and we already have lowercase you know dollar sign post that is the correct blog post so in the body of our function we can just return a view and we haven't created the new blade template yet we can in about 10 seconds from now let's name the new blade template like edit Dash post some semicolon let's give this a second argument of the data that we want to pass into the blade template so we would have an item I'm just naming a post you could name it anything but then arrow symbol and just give it dollar sign post so the cool part here is laravel is going to see that number that's coming in from the URL it's going to fill in the metaphor for what a blog post is right on our model so it's going to perform the database lookup for us now in our blade template we'll have something called you know dollar sign post so we can save this and now let's go create the new blade template so in resources and then in views I'm going to create a new file in the views folder let's name it edit Dash post Dot blade.php I'll just type Doc and hit tab to get a bit of starter but then in the body content I'll have a heading level one that says edit post you know and then below that I'll have a form the action can be slash edit post slash you know double curly brackets look inside it for the ID but the idea is that this time this form will perform a post request so when you submit this form it's going to have the new title and body that you would want inside the form though let's start out with a csrf token you could absolutely leave this as a post request or with laravel we can say you know method put let's have an input for the title so name equals title value equals so we want to pre-populate it with the existing title value so double curly brackets and then dollar sign post look inside that for title and then below that let's have a text area for the body content so the name would be body we don't need ID columns or rows and then the existing value in between the text area sandwich and you just double current the brackets dollar sign post look inside it for body then below that let's just have a button that says you know save changes let's give that a save and now if you refresh the URL right when you're trying to edit a blog post beautiful it's pre-populated with the title and the body content so now we just need to set up the request the URL pattern for when you actually send a put request right when you would submit the form so to set that up just jump back into web.php and to save a bunch of typing we can literally just duplicate this line we just wrote so I'm just going to duplicate it on the new duplicate copy we just need to change the type of the method for this request so instead of a get request right the URL pattern is the same but it will be a put request you want to update or you know put a new entity at this same URL and then obviously the controller method name instead of show edit screen you could have a method like we're just making up names here but it could be like actually update post so with that in mind let's save that jump back into post controller and let's have you know a public function named actually update post so once again in the parentheses you would say uppercase post dollar sign post we'd also want a second argument so comma and it would be you know uppercase request lowercase request so this gets us the blog post that we're trying to update this gives us the incoming form data right like whatever the user actually typed in for their new values so back in the body of our function and first of all we need to do the same thing for this function as well if you're not the author of the current post you shouldn't be able to perform either of these actions right like this blog post is a brad blog post so if the Barks A Lot user tried to view this screen like if I took this URL and then in Firefox so when the Box a lot user tries to visit this URL it should just redirect them back to the home page instead they do not have permission to even view this edit screen and they definitely should not have permission to submit this form so on the show edit screen you can just wrap this in an if statement ideally if you know this was a 20-hour course about laravel or if I was going to make a follow-up video here on YouTube you would use something in laravel called a policy and you could use middleware to perform this same exact feature and that would be cleaner or more organized but in this simple video we can just write an if statement right here we can say if parentheses curly brackets just say if off user get the ID if that does not double equal sign post user underscore ID so essentially if you are not the author of the current post let's just return a redirect back to the home page oops okay but if this doesn't happen that means you are the author of the post so then this is fine I would just do the same thing in this function the actually update post function so you can just literally copy these lines paste it right here cool so if you're not the author of The Post what do we want to do we want to actually update the post so the first thing I'm going to do is validate the incoming title and body fields to make sure they're not blank so you know incoming Fields equals request validate give that an array we'll say title is required we'll say body is required if you wanted to you could strip out any tags from those values we've already learned how to do that in our create function down below so I won't bore you with that but I can just paste in those lines that we've already gone over and now we just want to actually update the correct entity in the database so now here's what's cool laravel has already given us an instance of the post model for this current you know the appropriate blog post so we can literally just say dollar sign post and then it has a method on it of update so we don't need to write a SQL statement and then just give this the data so dollar sign incoming fields and then finally let's just return a redirect back to the home page I realize there's about a hundred different ways you could set this up so it's cleaner you know so you wouldn't have to type this same line here and here but I'm just sort of thinking on the Fly and thinking out loud so the code is not perfectly organized but let's test this out so first of all if Barks A Lot tries to view this URL perfect boxlot doesn't have permission it kicks them back to the home page the Brad user though if I refresh cool now imagine if I want to add like three exclamations to the end of the title and to the end of the content I can click save changes and there you have it we actually performed that update beautiful now let's go ahead and set up the functionality so that you can delete a post so I'd start out in our web.php file to save typing I just duplicate this line at the very bottom and on the new copy the type of request is a delete request in the URL pattern is delete Dash post and then you know the ID number of the post let's change the method name so instead of this it would be and we're just making it up we can make up a method name of like delete post let's give that a save jump into our post controller let's on our class add a new public function called delete Post in the parentheses right let's fill in the metaphor of what posts we're talking about you know dollar sign post in the body of this function let's perform that same check right like are you actually the author of The Post in question so I would literally just copy these three lines paste it in and then so we don't have to type this in again here's what you could do change the condition to if it's true so like instead of exclamation equal equal we could say like triple equal sign so if you are the author of the post and then we could move the redirect to be below this so that it'll it'll run either way and but only if you're the author then actually delete the post right so we would just say dollar sign post the model has a method on it we don't need to create it of just delete and this is actually a great opportunity to go over the fact that laravel models they have awesome functions built into it that we don't even have to set up right like create update delete but you can add your own functions to models right like on our user model right we added the function named users cool posts but you and I didn't have to spell out you know a public function called create or update or delete beautiful let's go back to our post controller so with that saved if we refresh and imagine I want to delete this post that says you know another Brad 2 post click delete perfect it's gone for our final detail in this video let's set it up so that next to each blog post title it says buy and then the author's username because this is one final example for us to again learn what exactly a model is doing or why models can be so useful so to get started on this feature let's jump into our blade template our home.blade template so home.blade.php here's the heading level three with the blog post title so you could imagine it would say like you know buy and then the username there's just one problem we can't say you know dollar sign posts look inside the array for like username because remember if you look at the database for the Post table all we have on the post table is the ID for the blog post you know the date that it was created and then the title content the body content we don't have the username we just have the ID of the user account so I mean you could say like user ID that's just going to give you an a number like a numerical value right if we refresh you know by the user whose ID is two so the question is like how would we actually look up the appropriate user Row in the database like if you look at the users table and go aha the user with that ID their name is Brad 2 or Barks A lot how would you look that up in the database well the cool part is is you and I don't have to look that up in the database we don't have to write a SQL statement and perform a join we can just use the power of relationships in laravel so check this out let's begin from the perspective of a blog post so that's the model that we would go edit so let's go edit our post model file right post.php at the bottom of our class I'm just going to say public function you could name it anything you can name it unicorn but I think it would make sense to name it user so parentheses curly brackets in this function we're just going to return a relationship so return dollar sign this look inside it for belongs to semicolon and now you can read this as a sentence the file that we're in is a post so we're saying a blog post belongs to a user so we're going to give this function two things a comma B the first thing we give it is just our user class so user call and call in class the second thing we give it is the column that is powering the relationship so that is quotes user underscore ID in other words laravel is going to see this and now laravel can perform that look up in the database for us laravel can write the SQL statement and perform the join for us so with this in place just save it let's jump back into our blade template okay and now we don't want to you know put out the numerical value here's what we want to do let's in these double curly brackets you can completely empty them out we want to begin with our post look inside that for user and then you could look inside that for anything the name their email address but we would want just name so we can save that if you refresh beautiful so hopefully the idea of what a model is is starting to take shape in your mind the model is sort of this abstraction layer between what we want to do in the database it has functions for creating updating deleting but also we can add our own functions to a model to power relationships and that is going to bring this video to a close if you enjoyed this video you might enjoy my 14 hour premium laravel course in the full-length laravel course we set up a social networking app where you can follow other users have a home page feed of the users you follow you can upload an avatar image for your user account we set up a live chat room feature we set up a live search results overlay feature we learn how to automate different tasks in laravel so that they can happen you know every five minutes or every five hours we learn how to send an email when a user creates a blog post just all sorts of different features of the laravel framework right in a more comprehensive project that feels a bit more real world anyways if you enjoyed this video you might enjoy my full course you can get lifetime access to the course for the cost of about two trips to a cafe in the description for this video you can find a link to my coupons page with heavily discounted coupons to join all of my courses and you can see the newest one is the let's learn laravel a guided path for beginners thank you so much for watching this video until the very end I hope you feel like you learned something and stay tuned for more web development tutorials [Music]
Info
Channel: LearnWebCode
Views: 136,770
Rating: undefined out of 5
Keywords:
Id: cDEVWbz2PpQ
Channel Id: undefined
Length: 76min 13sec (4573 seconds)
Published: Wed Jan 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.