[COURSE] Laravel 9 For Beginners: Your First Project

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys as a part of my mission in 2022 to reshoot old courses and update them i have just reshot the free course laravel 7 for beginners i've recreated a similar project with laravel 9 with new thoughts with new microphone by the way which didn't existed at the time so in this video you will see that full course i decided to release it on youtube as well or maybe if you prefer it you can watch it on laravel daily the teachable.com it is still free just maybe more convenient for you to mark the lessons as complete here on youtube you will still have sections in the description so you can click around but maybe as of course it's more convenient also you may check out my other courses these are the older ones which i will reshoot one by one in upcoming months and here are the latest ones including alpine js inertia vue 3 with spa live wire and stuff like that and the best way to get them all is yearly membership and by subscribing to yearly membership you support these youtube videos which i can shoot for free and publish on youtube now let's get to the course for the beginners probably you are not the very beginner if you're watching this channel for a while so you may pass that course send the link to someone who wants to learn laravel from scratch enjoy watching and if you have any comments shoot them below the video in this first lesson we will install new project with laravel we open up the documentation and installation has quite a lot of information but interestingly enough there's no one way to install laravel and you can find different information on different sources the official laravel documentation is mostly based on a tool called laravel sale so for example if you click getting started on mac os it requires docker desktop to be installed and then you need to run laravel sales sale up command to run your new laravel project you can read more about laravel's sale separately in the documentation and how it works but this is not what we will do in this course my personal preference to install laravel is with laravel installer which existed almost from the very beginning of flowerville laravel's sale is pretty recent newcomer to the scene from what i remember it was released with laravel 8 and the idea here is to use docker for all the installations but for me i preferred old working way which doesn't require docker again it's a personal preference and there's no one way to install laravel but i will proceed with my personal way you may like it or not you may read more about laravel sale and those official recommendations on getting started but i will proceed with installation by a composer installation via composer requires you to have composer installed on your machine and generally on your machine you have to have web server but if you work with php before laravel i assume you do have web server already on my macbook i have and i use laravel valet as my preference again there's no one tool here for mac people laravel valet and laravel sale are probably the most popular choices for example if you're on windows number one choice from what i've been reading online is laragon so you can try that so you need to have a web server and then you need to install composer composer is a dependency manager for php which means it will install all the dependencies into your project including laravel laravel is basically just a package on github it's github.com laravel framework and you can install that into your php project with composer i will not show how to install composer because it's already on my machine you can click getting started and depending on your operating system you run the commands that are listed in the documentation and configure the composer what i will do in this video is install laravel so we get back to this and we install laravel installer composer global require laravel installer which i have already run on my computer so to create a new laravel project with installer all i need to do is run laravel new and then the name of the project which will be a folder created as a subfolder so in the terminal i run laravel new and let's call our new project project it will create a project subfolder and with my laravel valet by default it will create a domain locally project.test which i will just run in the browser so if i run project.test i have laravel homepage currently version level 9.7 and we already have laravel installed if we open up phpstorm with that project the main file that we will start with in the next lesson is routing so you have home page which leads to welcome file and welcome file is in the resources views welcome dot blade which contains all the html that you can see on this home page now let's dive into the code and see how that welcome page actually works now we need to understand how that all works so if you want to define the route the url you do route get in the very basic example then your url which is in our case home page and then a callback function php closure function which returns the view view is a file in laravel language called laravel blade it's kind of html with variables and welcome means that file is in the resources views welcome which has an extension this is important welcome.blade.php so it's not welcome.php it's welcome.blade.php and inside of that blade as you've seen just previously it has html mostly with some blade syntax variables so if statement then auth statement which means the user is logged in then another if statement and a few more variables here and there let's try to edit something and you will see that it actually works so let's change some text for example laravel has wonderful documentation level framework let's add that we save then we refresh our home page project.test and you can see the text update at laravel framework so there's no need to recompile anything or run some terminal commands you just edit the blade file and the changes appear here similarly you edit the routes file to have another url for example let's duplicate that route get second page for example then we have second blade and let's do welcome blade let's do file save as as second.blade.php in the same folder and let's change that to second blade laravel second framework something like that it's just a dummy example of some second page and then if we run second in our browser slash second then we'll have laravel second framework as text and for example if we remove that home page what happens if that route doesn't exist so isn't available in the routes web file then you will see an error 404 not found so anything that you just run here by default will throw 404 not found if it's not present in the route file which is by default routes web now let's replace the default laravel homepage with some kind of design and i found a bootstrap theme really basic blog homepage it's your personal choice what design to use whether it's bootstrap or tailwind which became really popular these days but i'm choosing bootstrap because it doesn't have overhead of running npm commands to compile the css by default of course again you can deal with front end in various ways but i will show you the most simple example because in this course i don't want to dive too deep into front end i want to stick with laravel as a back end with any kind of design which is different from the welcome default home page so the blog looks like this i've downloaded the theme free download i've opened sublime text i use by the way sublime text personally for html editing and something really like text based really simple and phpstorm for php project so this is index.html and i will copy and paste it into phpstorm into not welcome blade but let's create another view in resources views new file index blade php let's call it index we paste that html and let's actually delete both of those second and welcome blade i delete them and in the route i will change the view welcome to view index like this and now for refresh our page the home page looks like this so it shows something but without the design for the design we need to add the assets so the theme contains fav icons styles and scripts and we will copy and paste those files into public folder so how laravel works in indexblade for example on top we load css style css and then at the bottom there should be js this one bootstrap itself is loaded from cdm so we shouldn't care about that but how do we load scripts and styles from resources views folder how do we reference those files those files by default should be in public folder and we copy them as subfolders into public folder i will use commander on my mac so assets css and js copy into here and then we reference them as asset with a blade function helper so blade language requires this syntax for any variable or any command and in this case we'll use a helper called asset and cut and paste inside this will return the full url of project dot test slash css slash styles css and we do the same thing for the js so asset and then js script js here like this and also i probably forgot fab icon yes so asset like this asset assets 5 icon paste and now if we refresh our page we refresh and we have the full design of course it's a static home page for now and we will work on that in the future lessons but what i wanted to show you in this lesson is how to reference the styles which should be in the public folder instead of that you could potentially also do something like this so reference the files from the home page but that requires you to have public directly in your domain name so then you cannot place your project in a subfolder for example i'm not saying i would recommend to do that but generally this is more strict asset compiles the url no matter where your project is actually located on the server so if we take a look at the view source here as you can see project.test.css refers to public folder in your laravel project and then whatever comes after the domain is the subfolder and the file in your public folder now let's create a few more static pages for about and contact for example and we won't create the blog in this course we'll remove the block so in the index blade let's remove the block as link and then we have home about and contact so let's create the about we will do file save as and have about blade and here you can see that there are repeating things so header and footer and menu and later in this lesson we will talk about layouts but for now let's create three static pages so instead of welcome to blog home we have about us and for example about us text or let's actually leave that in header and in the container let's make it like this so full row and paragraph and we will remove everything that is related to the block because we don't actually need it we don't need any widgets this should be okay so we have about blade and in the routes web let's duplicate that and have url about which points to the about blade again in the resources views folder and now if we go to slash about let's see how it looks we have slash about great about us and then about as text in the main section of our page in a similar fashion let's create contact and i will show you one more trick with routes so we have contact blade and let's change that text to contact us and contact us text and in the routes web we could do copy and paste into another contact but there's a shorter way for now let's make it a longer way and have contact which works but if you have route which just points to static html to static blade file there's route view which is not requiring the callback function another parameter it has two parameters so route view url and blade file name that's it so we can shorten our routes to about about like this and then contact contact let's actually duplicate that okay contact still works about still works home page still works great and now let's take care of the repeating part so in both index blade and in about blade and also in the contact blade the menu is repeating that all html is repeating so if for example you want to change something like start bootstrap like add start bootstrap here it will change only in the about blade but not elsewhere so let's add a layout here where the main the common things would be placed and then inside of each blade we will take care only of the content of that blade file so let's file save as index blade to resources views slash layouts for example this is optional but i prefer subfolders for that layout and let's call it app layout app blade and we will leave everything except for the main part except for this part so header and container will be dynamic and dynamic means that we need to use a blade command called yield and yield is with a parameter of section name it will be content let's call it content and we remove all of that until footer footer remains in the layout so navigation menu and the footer remains but we have index blade which is empty and we paste only the block content and we wrap that into section so add section content which will be the beginning of the section at the end we'll have end section you will see it more clearly when we get to the about and the contact pages so we get the section for the index for the content which corresponds to yield content so the same name and we need to specify that we extend the app layout which is extends layouts dot app this is dot which is a subfolder so we extend the app and inside of the content we have this and in the about blade we would do the same thing so we need to leave header and container as it is but we remove everything else so footer html everything and do the same thing extends layouts app and inside we'll have section content and section something like html tag with beginning and an end and let's actually copy and paste that into contact blade and we just change that to contact us and contact us text and now we can go to the main layout which is app plate and actually create the links so href will be not just home but you can of course do it like this so slash then slash about and slash contact but a common behavior and advice behavior for laravel is to use routes and route names so there's laravel blade helper called route and you can call the name however you want so route home then we have let's copy and paste it from here route home then route about and route contact and we will assign those names in the routes web file here to each of them so this route will be called home this will be name about and this will be name contact something like this and now let's try to navigate we refresh we click about we click contact we click home so we created three static pages which extend the same layout and the content is different so we've built a static home page and a few pages but now let's talk about backend about the database structure and the data at all how laravel deals with that for database structure you don't need to create database tables manually in your mysql client for that laravel uses a concept called database migrations so you describe your database schema in migration files and then you run the migrations which create the database let's take a look at the default migrations from laravel they are in database migrations and there are four files generated by default the last three are not that relevant for the beginners but the users table is really important and it is suggested suggested the user structure for you which is probably relevant to any project that has users and even if you don't know the structure how migrations are written it's pretty readable so you need id field the table name is users and then fields string name string email unique so emails cannot repeat then timestamp verified add or not by default nullable then password remember token is specifically laravel thing to use for remember me checkbox and then timestamps which means create it at an updated ad field kind of system fields for every database table now how can we use those migrations to create our database by default the database is empty i've just created a database called project in mymysql client which is table plus locally but that doesn't matter you can use whatever mysql client and then in the terminal you run a command php is on migrate it executes all the migrations from the database migrations folder let's take a look at others for example password resets which is used for forgot your password function and a few more system tables so if we run php autism migrate see for every migration it's migrating and my grade ted so start off the process end of the process and how much it actually took and now if we take a look at our database we refresh and we have all those tables created so user stable empty by default but structure is created important note here to run the migrations and i'm shooting this part of the video afterwards because i remembered i didn't mention the configuration so how to connect to your database if you have for example database server locally it is done in config database php so the credentials to the database and there may be multiple credentials in one laravel project you may have sqli driver for your tests for example you may have the main mysql driver with a lot of parameters also there's posgrasql sql server with additional drivers but what we do need to know is env what is cnv in laravel project there should be a file called dot env so env is the extension it's not env.something it's dot env in the main folder so here and it contains all the environment variables that's why it's called env short for environment it is created by default in every laravel project and it should be uploaded to the server when you launch the project live and by default it is copied from file.nv and in the very beginning the laravel installer when i called laravel new project replaced some variables with the values of for example app urlproject.test so this is the project and then database project and coincidentally this is exactly what the data is on my server so the database is called project and these are the credentials default from laravel valet which i use locally for the web server so for your case you need to change the main credentials here in env file or if you don't have that env file for whatever reason you need to create that locally so what happens for example if you don't do that and database name is for example default or whatever what would happen when you run php artists on migrate let's try to do that php is on migrate and you would have error unknown database default so to avoid that you need to provide the credentials here to connect to your database and in general there are more system environment variables for something like email sending this is often used for external applications like aws pusher or redis or whatever which are optional and many of you will not use them in the beginning but generally you need to know that dot env file contains the variables and then those variables are used in the config files of laravel project including config app for example for app name and in config database some of the variables are hard coded and some of the variables have values from env file an env function helper has a second parameter default so if you don't have env file or if you don't have the variable like dbhost by default it will be equal this value now let's get back to running the migrations as you can see what is in laravel language as id becomes big integer in the database string becomes varchar255 and timestamps become created as an updated ad as timestamp so laravel has its own kind of language of migrations how to describe different fields in the database and let's create our own migration we will use that four categories of our blog so this is on the right hand side let's create a database table categories to create a migration we run php artisan make migration and then you can name migration however you want but a typical name for creating table is create underscore table name which is categories and underscore table it generates a class a new class as you can see here create categories table and it generates automatically schema create kind of a template with by default two fields id and timestamps and for example our category will have just the name so we add table string name of the category every migration file has two methods up and down down can be run if you want to roll back the migrations how does it work when we run the migrations again php autism migrate it will run only the migrations that were not run previously for that in the database table migrations we have the list of what migrations have been run so those that were executed are already here kind of logged as executed finished with batch number if we run php autism migrate again it will run only the categories table migration and if we refresh the full database we have the categories table here now with structure great and in the migrations table if we refresh the data we have batch two and we can roll it back by running php artisan migrate roll back and it will roll back only the last batch which is batch number two and it will execute the down method in all of those migrations so roll back and now in our database for migrations we don't have this and we don't have category stable anymore so it was rolled back and it may seem for some of you that this migration system is an over complicated thing instead of just creating the table in phpmyadmin or table plus or whatever is your sql client but the logic here is that migrations could be run elsewhere on another server for example you created your database locally then you push your project to github to be run on testing server or on live server or for your teammates for example and how would they create the database on that server would you export the sql and then run it what about the changes on existing database if the data is already live so the goal is that you make the changes you push your code and then whoever needs to update those changes on their database on their server just run php autism migrate which executes only the last changes since migrations were executed previously there are a lot of things to be said about migrations in detail so you can read official laravel documentation but this is an overview how it works and how can you create database tables as easily as this next we will try to work with that table get the data and update the data so we've created our categories database table let's try to get the data and fill in the sidebar of categories we will get familiar with a concept called mvc model view controller so three layers which are responsible for viewing the data getting the data and controlling the routes the url let's begin with showing the database i manually for now manually i've created four categories later in this course we will create an admin panel to manage them but for now let's just put in the categories on the sidebar in our routes web we have home for index and let's open that index blade which should contain our categories static for now so these are posts with pagination and here we have site widgets with this list of static categories from the original theme let's replace that with categories from the database but first let's replace that with static categories from the laravel application we will replace the index blade and introduce a thing called controller that syntax of routing url attached to the view directly is used only for static pages but if you want dynamic data you need to introduce a controller which would get that dynamic data and pass that to the view let's generate a controller make controller you will run a lot of artisan commands with laravel of make something run something so php artisan is a great helper so make controller and let's call it home controller like this and one controller may contain multiple pages multiple methods for now we'll have one method so let's open home controller which was generated it's just empty laravel class that extends the controller and we will create a method public function index let's call it for the home page and it will return a view so the same view of index it would return the same as it was in the routes but we will have the data passed as an array and for now let's hard code that data so categories equals array of categories for example category 1 and category 2 for now and we pass that as categories equals categories or to make it clearer what is what let's call the variable all categories and this will be the variable available in the blade files in the index blade php so if we open that index blade instead of this we can do a for each loop in the blade a lot of commands and directives start with add symbol and add four each works similarly as a php loop for each of the categories as category and let's do and for each and for each like this and we will have category named here category to show the variable this is the syntax and let's remove all of that and let's remove the second column so it will be all in one column called sm 12 for example so we have our blade file ready we have the controller that passes the data to that blade the final piece of the puzzle is the route to change that route view to route get back to route get but instead of having index here we will have array of parameters first parameter is the controller name second parameter is method so we'll have home controller which is autocompleted with my phpstorm home controller class and then the method is index let's put it on a separate line like this we save and let's refresh our page we refresh and we have our categories here on the right from the controller so this is how it works with routing controller and the view let's introduce another layer which is model which is responsible for getting the data from the database to get the data from the database here instead of all categories there are two ways first way is to call the database directly with a class called db that comes from illuminate support facade which will be auto completed here by my php store and you can provide db table categories and then call some methods for example method get which will just get all the data and then you assign that to a variable all categories and then all of those categories will become objects so instead of just all categories as array now we have categories as category and then category becomes an object so we need to specify the field category name so now if we refresh our page we refresh and we have four categories now from the database so one way is a db so-called facade class but a more appropriate approach and more common is to create a model so-called model which is an eloquent model eloquent is a database layer of laravel kind of a layer between the laravel framework and the database it has a lot of features a lot of methods that's why it's more convenient to use eloquent instead of dbtable to create a model run the command make model and typically model name is the database table in singular form so if we have categories then the model is category and it will by default work with categories table let's open up category model our new model it extends the model from eloquent this one you can ignore has factory for now we don't really care about that and you can specify what table does it work with you can specify table categories but as i said by default it is plural form of the model name so you don't need to specify that it will be by default and then in the controller instead of this we can do category model which will be again autocompleted by my php storm method all that's it so we don't specify the database table we don't specify get we have all categories and if we refresh our page it should still work all categories are here and now we don't need the db here and actually we don't need the request here which was generated by laravel by default and we have our categories listed on the page from the database so as a summary it is really important to understand the whole workflow request lifecycle of mvc which is route controller model and view so routes web has the controller and the method index inside of that method you may or may not use the model to perform some data operations and then you pass some data into the view which is then displaying that data as blade language with variables this is the core fundamental of almost every laravel page in very simplified version now let's take care of the posts by category so here in the main section we have the list of posts and we will create a model for that as we did for categories but also we will define so-called relationship so every post should belong to one of the categories and then we will build the links to the home page with category as a parameter so let's start with a data structure and we can generate a model php artisan make model post and here i will show you a trick we need migration for the post so database schema and the model for the post and you can create two in one make model post while also creating a migration dash m and it will create both it will by default create posts table migration again plural for the post model name and we can fill in both so post stable we have what fields do we need actually string title table text for longer text which is description or post text let's call it post text when it was posted will be defined by timestamps and we need to have a relationship which category does it belong to to create that relationship of course we need to have a field name so you can do that as integer and let's call it category underscore id but to create it as a foreign key on the database level along with the field we need to add foreign id there are multiple methods to define foreign ids as you can see in my php storm autocomplete but i will show you the most typical one which is foreign id and then you need to name the field as singular form of the foreign table which is categories so we need category id and then you define a thing called constrained which means that it refers to the id field on that categories table we can run the migration again php is on migrate and we will have our posts if we refresh our database we still have the categories but on the left we have posts empty for now and behind the scenes i've created a few dummy posts again for now we're talking about getting the data later we will talk about how to create that data as admin panel but for now let's get those posts on the home page so in the same index controller home controller story index method alongside categories we do posts so post post you can do all or you can get the latest post right so order by id descending for example or you can do latest so again eloquent has a lot of features and a lot of methods to help you get the data from the database so i will do post latest get and then we need to pass that alongside categories and here i will show you another trick so for example let's have that as array but add post equals post and imagine we have not all categories but the variable with the same name and there's a shorter way to describe the same thing and that's a php trick it's not laravel or eloquent so if we have array of the same keys and the same values then shorter way is to use a method called compact php compact categories and posts like this and we don't need that array anymore so it would be something like this and now let's show those posts in the index blade somewhere on top we had those posts let's actually delete the featured post because we don't have the functionality for that and let's just do for each of the blog posts we will do for each of posts as post you are already familiar with that and let's remove that one and add and for each here and each post will have dummy image let's leave it as it is then we'll have post created ad post created ad then we'll have post title post title and let's show the description the post text as fully you can make it shorter like first 50 symbols or so and let's leave everything else as it is let's delete all the other hard-coded posts and let's delete the pagination we will not discuss that here and let's actually even delete the search widget because we won't implement it either in this course and site widget is also irrelevant we save and let's refresh our page we refresh and we have post 1 post 2 3 and post 4 directly from the database and now let's add a parameter of that index blade let's put a link to the category which will be linked to the route route name of index which comes from the routes web this one actually it is home sorry route home with some parameters and there are a few ways how to define the parameters for the route but we will use the easiest one not even laravel but php parameter so we have route and then we have question mark category id id equals category id like this so this will be the link and then in here in the home controller we can filter posts by where category id so category id equals we get that category id with laravel helper called request request category id and then we have latest and get let's format it and let's refresh our page we should have a parameter here empty home page why because we don't have category id as a parameter so there are no posts but if we click category id as you can see category id one here and now we have the first post from the first category from the database it is this one if we click category two we'll have two posts so that is working and finally let's fix the home page so it wouldn't be empty it would show all the categories i will show you one trick with eloquent it's not really for a beginner but so you would understand the power of eloquent and why you should use that there's a syntax post when so some kind of condition which has condition would be when request category id exists so true or false if we have request category id then another parameter we add a callback function of what we should do with the query let's call the variable query and then we add the where condition but only in case of request category id existing we add query where like this and this is our final query let's reformat it like this and we refresh our homepage and we have all the posts but if we click category 2 or category 3 we have only those posts per category so now you've learned a bit more about eloquent and about how to get the parameters from the url from php now i want to talk about another way of routing parameters in laravel so i've seen how to catch the get parameters with question mark but a more typical way is to have parameters inside of the url so for example project dot test slash posts slash id of the post as variable so let's create that individual post page and you will see how to cache that parameter how to get the data from the database with eloquent and also i will show you a thing called route model binding to do that quicker so first let's generate a separate controller which would be responsible for everything about the post make controller post controller and inside of that we will have a method called show post for example and potentially more methods in the future so for now let's create public function show the parameter will be post id and inside of that we will find the post with eloquent we have a function called find which will automatically find by id field on the database and then we return a view we will create a view called post for example post blade and we will pass the post variable as compact as array and we donate the request here and controller is ready now let's create that post blade view and for that we will open about blade and just do file safe as it will be a really simple blade without any difficult layout we will just replace about us with post title which comes from post object post title and about us text will be replaced with post post title so we have the page and the controller ready now how to get that into the route how to get that parameter so route get we create a new route posts with a parameter and parameter has the syntax of this and we will name it post id and another parameter will be as here array of controller and method which is post controller autocompleted by my phpstorm and method show let's close the sidebar so you would see all the picture or maybe like this and we will assign a name to that route name for example posts show or something like this and that post id name should be the same variable name as here then that parameter would automatically be passed and in the browser let's try to load that url to posts one and we have post one without the text for some reason maybe i made some typo of course it's not post title post text refresh and we have post text of course the design is not pretty it should be margin and padding but that's not what i wanted to show you here what i wanted to show you is how to pass the parameter and how to catch that in the routes but also for such cases where you have individual record caught by id in the url eloquent has even better solution so instead of having post id you're expecting post already as an object and then in the parameter of show you type hint that it is a post object of model post and you define the parameter post as variable and then this happens automatically under the hood so we can remove that and we can just return the view and if we refresh the page it still works if we load posts 2 it worked so this thing is called route model binding because it's binding the model by type hinting the model object type with the parameter here also what it will do if that post doesn't exist for example if we load something else it will automatically show 404 not found page so the final thing we need to do in this lesson is to get those links we have route name let's actually use it we open index blade and we have for each of the posts here somewhere yep here let's add a link so instead of having this we will have a link to route with the name posts show and parameter post id so all the parameters should be listed after the comma as a second parameter of route helper so we save and if we reload the home page project test like this the image should be a link which will lead us to post one so this is how you pass the parameters to the actual routes and it is advisable to use route names instead of url because the urls may be changed in the future and the route names will stay consistent and you won't have to make changes for urls in all of the project in all of the files so route names make it more easily manageable until now we've been working with existing data and showing the data now let's take a look at how we can manage the data and create a simple admin panel to manage categories and posts and to do that we will create a separate project separate laravel project based on the same models the same database structure why we need to do that two reasons first laravel has starter kits so-called starter kits to help you with authentication and authorization so login and log out features and registration features come out of the box as laravel ecosystem packages the official ones and most popular ones are laravel breeze and laravel jet stream and in this course we will take a look at laravel breeze because it's more simple but it needs to be installed on fresh laravel project it wouldn't work on the project that we already have because we have our own routes our own controller our own design based on bootstrap and speaking about design that's the second reason the official laravel starter kits use tailwind css and not bootstrap so before in this course i've shown you how to work with very simple bootstrap theme to put everything into public and now we'll install laravel breeze based on tailwind css because it's now a recommended way in laravel you still can use bootstrap and for bootstrap there's a separate starter kit laravel ui which still works but it's not actively advertised and you won't find it in the documentation just because laravel creators don't really advertise to use bootstrap but if you prefer bootstrap laravel ui still works so i've installed a new laravel project fresh laravel project project2.test so if i open the terminal and scroll up this was my sequence laravel new project 2 so it installs all the composer packages then cd to the project and make models for category and post and then migrate everything so we have the database structure now let's create admin panel for that based on laravel breeze to install larval breeze you do composer require laravel slash breeze and by the way this is how you can install any package from composer all the package names consist of vendor name so company name and then the package name so we install laravel breeze it is installed in our composer json by the way important thing so you would understand how composer works in composer json there is a list of packages that are required there are some more settings but what we need to know is this list of the packages some of them or most of them come directly from the framework including laravel framework itself as i mentioned it is a package as well and now we installed laravel breeze so when you do composer require what it does it adds the line here and then installs that package into a vendor folder so all the packages exist in vendor then company name vendor name laravel for example and then breeze and all those packages work kind of like in clues which you shouldn't touch so you shouldn't edit anything in vendor folder directly to extend our customize and package you need to read the documentation of that package for opportunities and features there so this is how composer json works for php packages and now let's install laravel breeze functionality so we have installed breeze itself in the composer now let's execute php autism breeze install it will generate the routes the views and some more functionality for us and then it says install successfully and i will show you in a minute what it installed but to have front end compiled we need to run npm install npm run dev i will just blindly copy paste it running npm commands and how it works is kind of outside of the course here of the course scope what you do need to know is that you need to be able to run npm commands so build successful to be able to run that you need to have node installed and npm installed so if you don't have that check the documentation for those but what it does it compiles the front-end assets so npm install works similarly to composer install or compose require it takes package.json file so composer json is for php packages for back-end package json is for front-end something like tailwind alpine js laravel mix and others and then install it all not in vendor so vendor again is for back-end and node modules is for front-end packages and npm run dev compiles the resources js files and resources css files into public folder the one that we already worked with in the beginning in the bootstrap version now we have css app css compiled and js app.js compiled and minimized and now we can refresh our page so we have project 2.test homepage almost identical with only difference those links on the top right so by installing laravel breeze we have login functionality including the form then back to home page we have register and i will try to register i will use fake filler chrome extension i register and i land on the dashboard inside so just by installing laravel breeze we have login and registration functionality with a simple design so i can also log out and it all works for us now how does it work what breeze actually generated so if we go to routes web file we see the same welcome from default laravel and this is new thing that was generated by laravel breeze the dashboard which is protected by so-called middleware auth which means only for logged in users and also name dashboard and then inside of routes web we include another routes file from the same directory which is auth.php and it contains more route get statements including route group so a few things that i need to explain here route group is a functionality where you can group a lot of routes into a group assigning some kind of set of rules to that group for example middleware guest means only for not logged in users so if the user is not logged in we have route get register which points to registered user controller create form and if you click to that controller and see what's inside create just loads the view form and auth register is just a blade file then on top of route get there's route post so post method of http works in the same way so for example if we open register.blade.php there are some weird things like x something which are blade components this is outside of the scope of this course for beginners but what you need to know is this for method post to action of route register and inside of that store method we actually validate the data and i will talk about that quite soon about validation we create the user so this is another eloquent function how to create the user with user model and then we redirect return redirect we don't return the view return redirect to the url which is home which is in one of the laravel internal files which is slash dashboard so this is all generated mostly by laravel breeze all authentication file with a lot of routes to registration login forgot password and then also there's email verification log out and a few more features which you may not even use in the beginning so if you want to generate all of that quickly use laravel breeze as a starter kit now let's create our administrator user and for that i will tell you about concepts like factories and seeds so with database migrations talk about the structure of the data tables and columns but there's also database factories and seeds to seed the data some fake data or some real data so for example database heater which is by default in laravel may create you fake temporary users like for example in this case commented out code load the factory 10 users and create them that user factory is in database factory's user factory and this is the definition of that fake user to be created it uses a library called faker which is not a laravel library it's php library and it is already installed here in that extends factory class so you don't need to define this faker it's already here and this means that generate the user with name of faker name email of unique safe email password is hashed version of password so if we uncommented in the database heater this line and we run php artisan db seed look what happens database seeding completed successfully and in our database so we have our project to database that i've created we have users with generated fake users those two were from my manual testing in the previous section of the video of the course and these 10 were generated automatically as you can see with created at the same time stamp so this is generally the concept of seeding the data so you have database cedar inside of that you can call the factory in the factory you can define your own rules for fields and then you can add more factories generate fake posts generate fake articles categories or whatever to make it a bit more structured there's a concept called seeding file seeder class to generate a cder class let's actually generate one for the administrator we will do php artisan make cedar admin cedar for example it will generate a file in database seeders admin cedar and it will have its own run method let's actually copy and paste from here user factory create and we will create one user and to execute that admin seeder from database heater we add that to the list as this call admin seeder class will generate one user but we do need that user to have some kind of admin field or admin condition so let's add a new field to the users table for our simple case it will be called is admin true or false boolean field and for this admin we will fill in as true and in here you will also find out how to generate migration for some change of the data new migration doesn't have to be for new table you may make changes as well php autism make migration and a general rule of thumb to name that migration is add field name for example is admin to table name users table like this then laravel will generate migration with the text of schema table it's not schema create remember for creating post there's schema create which is creating the table for any changes their schema table and then you may add fields like just table string or table whatever in our case it will be boolean field is admin by default false so default false like this and we do php autism migrate which will execute only the last migration here like this and then in the factory in our administrator we can override some fields some default fields by providing the array here so create is admin equals true by default and let's run our seeds and let's see what happens so php artisan db seed again and see the difference if there's a separate seeder file it is seen in the list as seeding and seeded similarly like migrating unmigrated but if you execute the factory inside of the main database heater that is not in the terminal so that's another reason to probably use cders as separate classes now let's see the database we refresh we have 10 users generated from id 13 to 22 and id 23 should be with is admin 1 exactly as we specified here by default the password of all those users is password it's not secure i know it is defined in the user factory here i already showed you that you can change that or you can override that but as a proof i will show you that actually works so let's log in with that user copy and paste email password and i'm inside the dashboard so generally this is how seeding work with factories in laravel of course you can dig deeper and read more in the documentation there are more possibilities but this is an overview to get you familiar with that concept as a beginner now let's build the page to manage categories instead of that dashboard or in fact on top of that dashboard let's open the navigation blade which exists in laravel breeze and let's add a link for that we have a blade component but it's actually the same as you would add just a general link so href to the route of categories index and i will show you why index in a moment and let's add categories here and we need to copy the css classes off that link and we can do that from nav link component blade from here for example let's just copy the classes these are tailwind classes if you want to find out more about blade components you may read about them i thought i would skip that topic in this course for the beginners so if you want to read about more xnav something read the docs about blade components so we add a class and we have a link for the categories now now let's build that route for that route you would think we will build a category controller with index method and that is true but in laravel if you have a plan to manage the model so have create form edit form and stuff like that it's common to have so-called resource controllers so if you generate a controller php autism make controller category controller and add a parameter dash dash resource and also assign a model which to manage model equals category let's see what happens controller creates successfully and if we open that category controller it automatically generates seven methods index for the list of the categories then create form store is the submit action of that form then show is the single page of that category then edit form and update action and destroy action so seven typical methods for every resource controller and then you can attach the route to that controller just by doing route resource so it's not route get or outpost it's route resource which in itself contains seven methods by default so categories and you assign the controller you don't need to assign controller and method you assign full controller category controller class let's close the sidebar so you would see like this and then that resource controller has a typical rule of names which is categories dot something and you can see that in the official laravel documentation so route name of categories index is exactly what will be in the index method of category controller let's fill it in with something really simple for now return whatever text and let's refresh the page so i have refreshed the page and i have categories on top of menu item and if we click that categories we have that text aaa so we build the category the route the controller now let's build the actual page to show all the categories we get back to our category controller and we repeat almost the same thing that we already did in the previous lessons we do categories equals equals category model all categories and we return the view let's call it categories index with compact of categories if you want to have blade files in subfolder like i will do in this case so there will be categories subfolder and then index blade file you put the dot here and let's create that categories index we have dashboard blade default from laravel breeze let's do file save as let's create a subfolder resources views categories and call it index blade and it has blade components for the layout which again is outside of the topic of this course so i will not edit that at all i will just rename the header of categories and instead of you are logged in i will have a table of categories table head row of name and then button so header would be empty and then table body and then for each of categories as category we will have a row off category raw category name and then there will be a link so duplicate and there will be a link to edit so a and then the link to the edit form will have similar route name rule so route categories we had categories dot index now have categories dot edit and then edit accepts the parameter of which category do we edit we will again use route model binding here so we can pass full category as a parameter and by default it will find the record by id and edit and let's refresh our page slash categories and we have name as a header and let's add some dummy category just for testing so categories add a row of test with some timestamp and refresh and we have test with edit link of course it should be styled but in this case i don't want to spend too much time on styling and css it is tailwind framework so you can add whatever classes you want if you click edit it will show empty page because the edit method is empty for now so we have index we have empty create store we have show and we have edit so let's build the edit page now from the controller point of view all we need to do is return a view of categories let's call it categories edit with parameter of compact category which is with route model binding here so it will find the category by id and we need to create that edit so let's do categories index file save as this is my favorite way to create new files based on other files so edit blade category edit will be the title and then inside instead of instead of the table we'll have a form let's show category name for now so we will test that it would actually work and show the category so we refresh and we have test as name okay let's build the form now form will have the method of post with action of route categories update this is another rule of resource controllers and parameter of that update will be category itself again with route model binding and then since we're doing update and not store not creating the record we need to add another parameter another input hidden field which is in blade called method and we need to provide that we have method put here so update and then let's build the input name for example input name equals name value equals category name so this one like this so we have value and then let's add a submit button button type submit save something like this let's refresh and of course we don't have any input styling so let's kind of steal those styling from laravel breeze we do have blade components a lot of blade components and again blade components is kind of outside of the course here but we can take css classes from input blade for example so i copy a lot of classes from blade component and add a class here and then the button we have the button blade as well and we have a lot of css classes in the edit blade let's copy and paste the classes into class if we refresh for some reason we do have the button styling and we don't have the input let's do input type text maybe then we'll have yep of course so we have the input and the submit button now let's take care of the submit submit with route categories update automatically points to category controller update here and category is passed with route model binding by default so we can do category update this is eloquent function category is an eloquent model of category if we click here we have eloquent model so have category update and with update you can pass parameters of what fields to update so name will be request name this is the syntax request is a parameter of what is posted with the form and request name or there are other syntax options like request input for example name with key actually let's put it this way maybe more readable so we update the category and then we return what usually in terms of update and store and delete methods the return is redirect back or redirect to specific success page return redirect redirect is a helper which has a chain of redirect to what and we use redirect route by route name categories index like this and let's try it out we refresh the page just in case let's rename that to test2 we save and we have an error called 419 page expired that is a good thing because i forgot to mention one protection for forms in laravel for every form that has post or put or other methods you should add a thing called csrf token like this it generates an individual token for that specific form which prevents multi-submission of the same form from elsewhere so someone could maliciously post the form submission multiple times to your server and this generates unique token for that specific form which means that this form could be used only once so if someone tries to update the category from elsewhere they would fail with 419 so let's refresh the form again test2 we save and then we have another error of name should be fillable and here we get back to eloquent model so to perform the update with fields we need to specify which fields are fillable in the category model as in any model you need to provide fillable array and provide the list of fields to be fillable in our case it's just the name and let's perform the same thing on the post model so wouldn't forget it in the future so what we have fillable we have title of the post post text from what i remember and category id like this and now if i refresh our page again we resubmit the form finally we are redirected back to categories with test2 updated data so now we finished with the update of the category now let's quickly build the create form and this will be almost copy paste so in the index blade of the list of the categories before the table let's add a link link to the route of categories create and the text of add new category let's add a few line spaces here so on the table if we refresh we have that add new category which leads to create which is empty for now so in the category controller let's create the create method return view categories create and we don't have any parameters because we don't have any category object yet we're creating that and we just open edit blade and i will do file save as to create blade like this category new category the form method post action will be to categories store and we don't need any parameters because as i said we are creating a new category we don't need method put because it remains posed for the create and we don't have any value yet because we're only creating that at the moment and it should be fine so we refresh create blade and we have the name to save saving is really similar to the update method so with update we had this to the create method to the store method actually we add this code category model because we don't have category as object yet so we need to use the facade create and same array name equals request input name like this and we return redirect back so i will just copy and paste redirect route like this let's try it out new name of abc we save and we have abc in the table again the table is unstyled but i don't think it really matters in the scores you can play around with tail and styles yourself finally the delete method which is called destroy in the resource controller and this will be a bit tricky because it's not a link it will be a button so we expand that td let's close the sidebar again so we have edit as a link but delete should be a form let me show you the syntax it should be a form of method post action should be a route of categories destroy with destroying what category again route model binding then we add csrf then we add method called delete and all we need to add later is a button to submit that button type submit delete and let's add a javascript for confirmation on click return confirm are you sure if that returns false then the delete would not happen we refresh and yes we do have that delete if we click we have the confirmation if we cancel nothing happens if we delete and click ok it would automatically fire the destroy method and let's actually implement it right away so we do category again with eloquent function delete we delete the object and then return redirect back copy and paste like this so we confirm and then our category is deleted so i'm running through that pretty quickly but i hope you get the idea how it all works there are eloquent functions like category delete and category update with specific fields or if it's empty category create one resource controllers have specific method names seven methods by default which you can refer to as categories dot something with parameters or without parameters depending on that url so with all of that we've built our crud our managing the categories page the link to that is in a separate commit and github repository so you can play around and see what is actually happening in the code if you miss something in this lesson now let's talk about middleware and authentication because we created admin user so why not we use that and assign the access only to admins for managing the categories right and we currently already have middleware auth which i mentioned briefly previously it means that this route is accessible only for logged in users and auth is the name of the middleware one of the middlewares that are offered by laravel directly you can view those middlewares in file called app.http kernel and there are middlewares like auth guest and others so basically middleware how it works it runs some checks before the url before the route and if that check returns false then it throws some error or it may redirect somewhere to the error page or something like that so in case of auth if someone wants to launch the dashboard while not being logged in for example i'm logged out and i'm trying to launch the dashboard it would automatically redirect me to login form this is how auth middleware works and we probably should assign the same middleware to our categories route resource because only logged in users should be able to edit categories so we could of course do middleware and then you can add middleware if it's a single middleware as string like auth or you can assign multiple middlewares as array comma some other middleware so for example authenticated and also admin user middleware which you would create by yourself but let's use a thing called route group which we briefly have seen in laravel breeze auth file and create a route group which would be only for logged in users so route group and the first parameter of the group is array of potential rules like middlewares and we add middleware auth and then the second parameter is a callback function which would contain the list of routes and then we get route get inside of that group and then on that specific route we don't need to specify middleware auth because it comes from the route group and then we can put that route resource also inside of the same group because we need middleware auth protection so again we don't need to specify middleware here let's try it out let's try to launch the categories here again i'm logged out categories and i'm redirected back to login so our middleware works now let's create our own custom middleware to check if the user is admin or not to do that we run artisan command make middleware and we call the middleware is admin middleware as you have noticed i like to put the suffixes the endings of the class so it would be absolutely clear what it is is it a controller is it middleware is it something else except for models so if you don't have any endings and suffix it's likely to be eloquent model so is admin middleware is generated in the folder app http middleware is admin middleware and the default structure is handle method which returns next of the request and before that return you need to add some kind of condition and if that condition is met you can abort you can redirect elsewhere so kind of override the next the middleware is kind of like a firewall or airport security check if you want to call that it checks something and prevents something so stop from fulfilling the request otherwise if it's good then it passes you through to the next request whatever it is it may be next middleware after that next gate of security check or it may just run the url and controller so here we need to check if our user is admin for that we have helper called auth another helper inside called user and that would return as user object logged in user object and then we have a field in the database name admin is the name of the field so if not is admin then we add a return so return some error and again another helper of laravel is called abort a board would show error page and stop everything else from happening and we can pass the status code of that abort which is 403 which is by default unauthorized authenticated so logged in but not authorized meaning don't have permission for that specific feature so we have our middleware then we need to register our middleware in the same kernel file which i've mentioned previously here alongside the existing ones like auth and other stuff we can assign any name for example is admin and just specify our class is admin middleware class which would be autocompleted by myphpstorm here on top and now we can use that route name in here the middleware name assigned to our route resource so look what happens we have group middleware by auth but inside of that group for specific route we can assign extra middleware like here middleware is admin let's put it on a different line something like this so now if i log in as non-admin user for example this one so i log in and i'm on the dashboard but if i click categories i should see 403 forbidden that's another word for unauthorized so in this section of the course i wanted to show you how middleware works both the default middlewares and auth is by far the most popular one and also how you can create your own custom middleware finally let's build the functionality to manage the posts which i partly did behind the scenes because it's almost identical to the crud create read update and delete of categories so to save you some time i did the same thing and i will show you the code now and we'll explain a few things more such as eloquent relationships and validation of the form so first what i did behind the scenes new link posts how it works table again unstyled table with just title and category we add a new post we fill in something we choose the category abc or xyz we save and we have the title and we want to view the category and this is where we will use eloquent relationships in a minute but generally it all works so i can choose another category save or delete the post in the code a new thing to you probably is route group may contain other route groups inside so middleware auth is for all of that set of routes and inside of that we have two route resources for categories and posts almost identical but with the same middleware of is admin and in the navigation blade i've added two links one of them is four categories and one of them is for posts again with post index and actually let's make an if statement blade also contains if statement and also has access to auth user so let's check if user is admin only then we show those links and if similarly to for each end for each we have if and if let's reformat that with phpstorm auto format and now if i'm logged in as admin i see those links and if i were to log in with non-admin user those would not be even visible that's a pretty typical security measure for the functionality hide that from the front end and also validate it from the back end so we have the link to manage posts which is route resource leading to the post controller and it's almost the same thing as category controller post all we show them then for the create for the drop down we do need the categories and then we pass them here then store is creating the post and redirecting back show is empty because we don't use that in this course in this lesson category all is also needed for the edit form and for the compact you can pass many parameters comma separated update happens like this and destroy happens like this almost the same as categories in the create blade a new thing maybe to you for the form we will have category drop down which is select and then another for each in fact it's not new to you because you have seen for each before so for each of the categories every category is an object so we assign the value of id and show the category name here what would be new maybe is in edit form in the post edit we assign the values of post title if it is an input text for text area we assign the value in the middle of text area per html specification and for the drop down it's a bit different we need to assign the selected based on some condition and in laravel 9 pretty recently they introduced a blade directive selected and then the condition of true or false before level 9 you should write an if statement here if this then selected option so this was an overview what i did for the post scrud and let's work on this one so for each of the posts we need to show the category of the post so in the database we do have a field post category id but how do we view the post category and then name for that you should define eloquent relationship and this is one of the most powerful feature of eloquent at all so in the post model you define public function category and are various types of relationships in our case post belongs to a category so it's a one-to-many relationship parent and child so category is a parent and child belongs to the category so we return this belongs to category class the model and then we can use post category function like this post category and then any field of the category database table of category model which is name in our case let's refresh we have no post let's add something and let's choose non-default category we save and we have category shown here but here there's a catch you shouldn't use the relationship like this let's add another category and there is a thing called eager loading to prevent too many sql queries to the database so currently our eloquent code would launch three queries one to get the list of the posts and then for each of the post it would launch the query to the database if we add another post there will be four queries to the database and imagine how many queries will there be 400 posts so let's fix that this is actually the most typical mistake of performance of laravel projects that i've seen by developers it's so called n plus one query and to test how many queries are there under the hood we will install a package composer require very famous package by this author barry vdh laravel debug bar it will add a bar under the page at the bottom we don't need to configure anything we just need to reload the page we reload and in here at the bottom you see a bar with a lot of statistics around your request your page and one of that the most important thing is queries let's zoom it in and i will make it higher so how many queries are there under the hood select from users is about authentication which is fine then we have select from post the list and then for each of the post we are loading the category which is a bad performance to avoid that in the code in the post controller we need to load those categories with the posts immediately in this request and instead of post all we will do with list of relationships in our case relation is category and then instead of all we have get so all works only if you have model and then all without any conditions but if you have at least one condition here then you need to change all to get so now we're loading post with category and then what eloquent will do under the hood is load all the categories for all the posts in one query let's take a look we refresh the page and instead of five queries we have three one query still for the users then we have select from posts and then it loads all the existing categories for the existing posts so this is just a tip maybe not for the beginner but i've seen it so many times from the beginners that you have to know the issue of n plus one query how to load the relationship this is called eager loading and also you need to use laravel debug bar to test the performance of your eloquent queries now let's work on the validation of the form so if you don't fill anything in here and you hit save you will see an error from the database column title cannot be no of course we can make it nullable in the database but basically we don't check if anything is filled in the form and let's do that of course you can do that from html level first so in create blade you can do something like input required so then if we refresh the page and we save the form you will have this but someone could send the request not directly from the browser it could be mobile application with api or just someone maliciously trying to launch the request to your form so you need the back-end validation as well for now let's remove any front-end validation and focus on the back end and this is what we need to do in the post controller store method there are a few ways how you can achieve that first you need to have the set of rules for each field and those rules could be placed in the controller itself or in a separate form request class first you can do request validate here and the parameter is the set of rules set of rules means array of field and then validation rule for example title validation rule is required there are a lot of available validation rules you can find them all in the documentation for now let's focus on those simple ones title post text required and then also maybe category d required as well so all of those required and now if we try to fill in the form or in fact refresh the form and not fill anything we save and we are redirected back so if validation fails what it does redirects back with error messages in the session we just didn't show them anywhere yet to show the errors i will use the official validation documentation code snippet displaying the validation errors and there is an example there is an errors variable object passed by default with the error validation and all we need to do is in the create blade before our form for example let's just show all the errors exactly as it is pointed in the documentation so if there are errors on multiple fields it will be a list of errors and let's reload our page we save and now we have title field is required both text field is required so list of errors of course again unstyled it should be probably in red or something like that but this is how you view the errors you can also show them individually after every field separately so you can read about that all of that in the validation documentation but what i wanted to show you here also in this video is to make your controllers shorter which is general kind of a recommendation so controller should not contain the logic it should be as small as possible and the logic should be elsewhere so for that laravel has a concept of form request class which replaces the parameter of request so we create a separate class with php artisan make request let's call it store post request and then we replace the request type with store post request auto completed by my php storm so add it here on top and then we move that array of validation rules inside of store post request in the rules method there are two methods in every form request class authorize which means authorized or not and by default i prefer to use true but it should actually contain the logic of if someone has access to that and there are rules and that's it so in the controller we don't need to validate anything validation will happen automatically whenever laravel reaches this method it will launch form request first and then if it fails it will redirect back with session errors otherwise we'll launch the method itself so we can try to do that refresh the page don't fill anything we save and exactly the same behavior but the code is in the form request class so that's it for this short introductory course your first project or in fact two mini projects with laravel and now you should have understanding how laravel works but you're not ready yet to create laravel projects on your own so you need practice come up with some kind of mini projects for yourself or for your friends or family or charity and then along the way get deeper into the topics that you work with with that i can help in 2021 i've created laravel learning path which contains a lot of topics kind of step by step we covered a lot of beginner level topics but you can still repeat them and dig deeper with links to the official documentation because there are a lot of things that we didn't cover on those topics and then you move on to more relationships for example belongs to many many too many and stuff like that and by the end of that beginner level you should create your own crud with more functionality than it was in this course so you can use that roadmap as well as the links to both repositories that we covered in this course and now your laravel career is just at the beginning so get to work practice more read the documentation read the tutorials watch my videos on youtube post your question on for example laracast forum or on twitter you can also check my other courses a lot of them are quite advanced so you may be not ready for topics like advanced laravel livewire or refactoring examples or graphql but there are easier topics like cues in laravel which you will need at some point how to structure databases some demo projects step by step like live coding for six hours so you can learn how to create real projects and how to create laravel api so choose and pick what you need there are 28 courses at the moment and the best thing the best deal how you can get that is to sign up for the yearly membership and i will fill in with more courses every month and by subscribing to the yearly membership you actually support my youtube channel where i publish videos daily for free that's it guys and good luck with your laravel career
Info
Channel: Laravel Daily
Views: 70,233
Rating: undefined out of 5
Keywords:
Id: 2bz5eleBj98
Channel Id: undefined
Length: 93min 29sec (5609 seconds)
Published: Sat Apr 16 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.