8 Common Mistakes Made by Laravel Developers And How to Fix Them [w/ Examples]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up developers it's Dari here and welcome back to a new video where we will have a look at eight bad habits that I see larval Junior developers make this video isn't made to bash anyone or to act like I know it better than you it's purely meant to help you guys out in your careers also this is my personal opinion everyone has their own take and there could be a hundred bad habits but these are eights that I see often quick pause I'm currently working on a new udemy course but we'll dive into laravel databases in eloquent if you think that there is a topic that should most definitely be included feel free to drop it down below in the comment section if you would be interested in a course or want to support a channel make sure that you follow me on either Twitter Instagram or YouTube to be the first one to find out when the course gets released the eight bad habits that I'm going to cover in this video have not been set in a particular order honestly it's very difficult to order it anyways because in most cases there isn't the right or wrong just Alternatives that might be better but even that is debatable number one on the list is separating validation from controllers in laravel and many programming languages and Frameworks it is common practice to separate validation logic from controllers there are honestly tons of reasons why separating validation logic from controllers is a good thing one of the main reasons is to improve the maintainability of their codes by separating the logic developers can make changes to the validation without impacting the rest of the code in the controller this makes it easier to modify the validation code and update it as needed without worrying about breaking any other part of the code another reason for separating the validation logic is to improve the readability of the codes when validation logic is mixed in with the controller's code it can make the code harder to read and to understand by separating the validation code developers can make their code more modular and easier to understand this can also make it easier for other developers to work with the code as it is more clear and more organized finally separating the validation logic can also make it easier to test code developers can create unit tests that Focus specifically on the validation part this can make it easier to identify and fix bugs related to data validation without having to test the entire controller so let's have a look at an example inside my task controller I have a store message right here which has one argument and that's the request object this object contains information about the request such as the HTTP method headers and body this can also be used to retrieve input data from the request such as form data query parameters and Route parameters through the request object that we have defined Insider argument we're saying that the following income and data should be validated so the name description and priority this feature is awesome but it doesn't really belong here in larville you can separate validation logic from controllers using the request class and the request class allows you to define the validation rules for a particular request and then pass those rules to the controller to use the request class for validation you first need to create a new request class through the CLI so right here let's perform the PHP artisan make me something which is named a request and let's name our request store task request if we hit enter you'll see that a request has been created successfully so let's navigate back to phpstorm because it creates a newly generated request directory inside their HTTP directory named requests with a store task request class now if you open it you'll have two methods the first one is the authorize method which needs to be set to true which allows users to make this request and then right below of it we have a rules method which is returning an array right here you need to define the rules that we pretty much defined inside the trash controller so let's copy the name description and priority rules and let's paste it inside the array if we then navigate back to our task controller we got to make sure that we put our store task request class to work by replacing the request class as an argument with the store task request class that we just created where we then could remove the validation part that we're performing right inside of our store method and larva will automatically validate the request before executing the methods if the request is invalid so a name description or priority is missing larva will return a response with the validation errors the second bad habit I see quite often is not following the single responsibility principle which is a programming principle that is part of the solid principles of software design this means that each class should have only one responsibility or job to do the idea behind the principle is that if a class has multiple responsibilities it becomes harder to maintain and modify the code which eventually will lead into bugs and Errors By following the single responsibility principle you can create a more modular and flexible code that is easier to understand and maintain it can also make it easier to test your codes as each responsibility can also be tested separately now let's have a look at an example where the single responsibility principle is not being implemented correctly I have currently opened a art controller which is located inside the art subdirectory right here you will see that the alt controller handles the login part of the application it handles the registration part of the application but it also has an edit update and delete method inside of it which will handle the user profile management so right here it basically handles both the authentication part and the user profile management to fix this you could create separate controllers for authentication and user profile management so let's do that let's navigate to the CLI and create three controllers we're first going to create one which handles the login part so let's say PHP artisan make me a new controller and let's name it art forward slash authenticate user controller then we need to create a controller for the registration part so let's say PHP artisan make me a new controller also in the art subdirectory and let's name it verify email controller finally we need to create a new controller which handles the profile management of a user and there's no need to place it inside the art subdirectory so let's say PHP artisan make me a new controller and let's name it profile controller if we then navigate back to phpstorm we should refactor our odds controller a little bit now let's start at the top with the login methods so I'm going to copy it and I'm going to paste it inside the authenticate user controller because it doesn't belong right here so we have a separate method which handles the login part then we have the register method so if we copy that you could basically delete it as well then we have our verify email controller which handles the registration part and finally we have the edit update and the destroy method which we could also copy delete it but we then have our profile controller where we could place the profile management by doing so we could basically remove our Global alt controller because we don't need it anymore since the code has been separated in different controllers Now by doing so the code is a lot easier to maintain but it also made it more modular and reusable the third bad habit is not using middlewares or not using them correctly of touching the not using Midwest correctly inside my previous tutorial as well but I see a lot of developers making the same mistakes when it comes to middlewares but I personally find it a bad habit to chain multiple middleware calls on the routes so as you can see right here we have four routes but they all implement the middleware art right here right here and right here as well by doing so your code can be difficult to read and to maintain while middle verse can be very powerful for filtering incoming requests and processing data it's important to use it right and only when necessary one alternative to using middleware chaining is to group routes together and apply middleware to the group as a whole this can make the code easier to read and to understand as well as easier to modify and maintain to group Drives together we can use the route group method so let's define a new route right below of it by saying route column column group the group method allows you to define a set of routes and apply middleware to the entire group by passing in a key value there as a first argument so let's pass in an array where the key will be the middleware while the value will in our case be odd because the middleware odd has been implemented on all routes right here now in this example we could basically replace all four routes that we have inside our route Group by passing in a second argument which is a callback function and we could paste it inside of it quick add-on you could add a prefix as an option as well by passing in a second key value pair where the prefix will be equal to the prefix of the first route which is admin so once we add it right here all of our routes inside the root route have a prefix of admin defined overall while middlewares can be a useful tool for filtering incoming requests and processing data it's important to only use it when necessary by grouping routes together and applying middleware to the group as a whole you can make your code more modular easier to read and understand now number four on the list is not testing your code and I don't really have an example for it but testing code is an important step in the development process not only does it help you to ensure that your code works as expected and is free from boxing errors it can also play a critical role in making sure that your application is reliable and performs well under variety of conditions one of the key benefits of testing code is that it allows you to catch potential issues early in the development stage this can save you tons of time and eventually money down the road as it is much easier to address issues where they are caught earlier in the process besides testing your code can help to identify areas where your code may be weak or vulnerable to certain types of input or situations my recommendation make testing a priority now number five on the list is not using database migrations correctly one of the biggest benefits of using database migrations is that they allow you to collaborate with other developers more easily you can pretty much share your application or migration files with other developers we can then apply them to their own local databases this makes it a lot easier to work together on a project and also makes sure that everyone is working with the same exact database structure I see and hear way too often the developers create their database structure through a database client or phpmyadmin another issue of not using database migrations correctly is that it can make it harder to roll back changes if something goes wrong if you're making changes to the database schema manually it can be hard to undo those changes if you need to with database migrations you can simply roll back to the previous version of the database schema with one single command now number six on the list as route model binding where I have an example for as well route model binding is a feature in larva that allows you to automatically inject a model instance into a routes action or a controller this can make your code more concise and easier to read as it eliminates the need to manually retrieve the model from the database and pass into an action let's have a look at an example let's start off with the route since we already have it open and in here we're going to define a route that will show a specific task of a user which will be a get request the endpoint will be forward slash tasks forward slash route parameter of ID and then we're going to send back a callback function now the route parameter needs to be found somewhere which can be done in the Callback function so let's pass in our ID where then inside the Callback function we could Define a new task we can set it equal to the task model where we're going to find one specific task based on the route parameter that is coming from the URL now once we have found our task we could simply say well return a view two tasks.show and add the compact method because we're going to compact the task now this could be done a lot easier with the help of Route model binding the ID parameter in a route corresponds to the ID column in the tasks table now larva allows us to replace a route parameter ID with a task model which will then search for a match inside the task table based on the route parameter that has been passed through and it will get the entire instance which will be set equal to our object task by doing so we could replace the eloquent call to our database since it has been done behind the scenes and we could basically return back our task directly this simply makes our code more readable as you don't need to manually retrieve the model instance from the database in your routes action it also makes your code more robust as larva will automatically handle cases where the model instance can't be found or doesn't exist now let's have a look at another example which is a more practical example inside our controller right here you can see that it's wrapping the route parameter of IDE which we could set equal to our task model task object which allows us to remove the call to our database we could basically return back one specific task resource now obviously right model binding can be harmful as well because it may not be appropriate in all situations one example might be when you need to perform complex queries or joints that involve multiple tables I personally don't think that the route model binding is the best solution for it in these cases it may be used to manually retrieve the necessary data from the database and pass it into your routes action additionally if you need to perform any validation or filtering on the retrieve data you may want to perform these steps manually as well number seven on the list is having bad naming conventions one of the most common mistakes that developers make with migrations is not following a consistent naming convention migration should be named using snake cases and it should include a timestamp to make sure that they are executed in a correct order which will be automatically added if you perform an artisan commands so let's have a look at an example we could basically open our database directory migrations and simply creating a new file inside our migrations directory named create tasks table dot PHP but as you can see in the directory structure compared to the other routes it doesn't have a timestamp added to it so what I always recommend is just creating migrations through the CLI where we could basically say PHP artisan make me a new migration and let's name it exactly the same so create underscore tasks underscore table we then navigate back to phpstorm you will see that it has created a new migration for a task table but it has included the timestamps another common mistake that developers make with controllers is not following the single responsibility Principle as I've mentioned before each controller should be responsible for a specific set of related actions and should have a clear and well-defined purpose there is a debate whether controllers and larval should be singular or plural but I always think that no matter which one you use you should be consistent now since controllers are also classes they should be named using possible case personally I think that you should always include the word controller at the end so let's navigate back to the CLI and let me perform a clear now let's create a new controller through the PHP artisan make me a new controller we're going to follow the Pascal case convention in a singular fashion ending with the controller so let's say post controller now models in larville should also be using Pascal case and they should be singular whenever you want to have a model that should work inside your post controller you should perform the PHP artisan make me a new model named post so singular and Pascal case when designing your endpoints it is important to name it is important to name your endpoints in a way that is descriptive and consistent let's have a look at an example Insider codes right here you will find two endpoints we have our song endpoint and article endpoint my recommendations is to always keep this plural so it should be named songs and articles by using descriptive and consistent endpoint names you can make your application more intuitive and easier to use for other developers consistent naming conventions can help you to make your quote more readable maintainable and easier to understand by following a consistent naming convention throughout your project you pretty much make sure that your code is easier to navigate through and that other developers can understand what each component of your code is responsible for finally we have number eight on the list which is not using eloquent in the right way when using larva it's eloquent over M it is important to understand how to use it properly to avoid performance issues one common mistake that developers make is not taking the time to learn by SQL properly before using eloquent and this happens due to people jumping way too fast into Frameworks before learning PHP and MySQL now eloquent is a powerful tool for working with databases but it's important to understand how it works under the hood if you don't understand how database queries work in MySQL you may end up writing inefficient queries that can slow down your application and cause other problems another common mistake that developers make is not taking advantage of eloquence built-in features and functionalities eloquent provides a number of powerful tools for working with databases including relationship management query Scopes and way more by taking advantages of these features you can write more efficient and effective queries and avoid common performance issues as well topics such as eager loading or overlooked which helps you to reduce a limit of queries that are executed against your database or even a topic such as query Scopes where you could write reusable query logic that can be applied to multiple queries finally it's pretty important to understand the limitations of eloquent and to know when and how to use other tools while eloquent is pretty powerful it's not always the best tool for every job in some cases you might need to use raw SQL queries or other tools to optimize your database performance now let's have a look at a couple examples and using eloquent the wrong way and I recently started using a tool named Tinkerbell and Tinkerbell is pretty much artist and thinker but on a lot of steroids it allows you to run code Snippets without refreshing your browser the first Common mistake and I've pretty much mentioned it already is not using eager loading if you don't use eager loading you will Define a new variable names tasks you will set it equal to the task model and you will get all values then you will probably try to Loop over it somewhere in your application over all tasks as one single task and you will end up echoing out the task name in the output you will see that all names of our tasks has been printed out now whenever you want to implement eager loading you will reduce the number of queries that are executed against your database it allows you to load related data in a single query rather than making multiple queries for each relationship we're going to refactor our query a little bit we're still going to access our task model but we're not going to chain the all methods because we're going to replace it with the width methods now the width method is an eloquent feature that allows you to specify relationships to load along the primary model this will definitely help you to reduce the number of queries that are executed against your database as it allows you to load related data in one single query rather than the all methods which makes multiple queries for each relationship so let's say that with our tasks we want to have the relationship of user with it and we need to change the get method to it now what this will do is load in all tasks with the relationship of user using only two queries instead of one query for each relationship now we can access our user as well by saying get me the task user and the username where you will see that all three tasks have been created by me which is called udari the second mistake I see a lot of developers make is not using the select method to limit the number of columns returned by your query whenever you need to Output one or two columns of an instance there's no need to select all models and simply make use of one or two properties just to print out the name or task description let's see how we could do this a little bit easier well not easier but better for our database performance we're going to select all tasks where where the priority is high and then we're going to select the name with the description and we're eventually going to change the get method to get all values and let me actually align this a little bit then inside our Loop we can simply output one specific task where you will see that we have only selected the name and the description now this could also be done without the select method that we have added right here so let's delete it but this will only be useful when you need to load related data with your primary model because it reduces the number of queries executed against your database when working with large data sets it is crucial to divide the data into smaller chunks and processing them iteratively instead of processing the entire data set at once this has a couple advantages first it can help avoid memory issues that can occur when attempting to process all data at once second it can improve performance by allowing the process of smaller subsets of data which reduces processing time smaller chunks of data makes it easier to identify and isolate errors that may occur during the process so here's how it works let's get rid of everything that we have and let's make a call to our task model and we're going to access the chunk method now the chunk method accepts two parameters the first one is an integer value of the number of tasks you want to get per chunk so let's say 100 and we're going to add a callback function then we're going to set 100 chunks every time equal to a task variable which we can use inside our goal by adding a for each Loop which will Loop over L tasks as one single task and we could finally Echo out one single task I don't really have enough data inside my database right now to perform the chunk method and see where the benefits are but it has basically divided the data into smaller chunks instead of processing them all with the all methods now this was it for today's video where we looked at common mistakes that developers make in laravel by following the best practices that we have talked about in this video you can write more efficient maintainable and scalable code for laravel if you do like my content and you want to see more leave this video a thumbs up and if you're new to this Channel please hit the Subscribe button
Info
Channel: Code With Dary
Views: 4,275
Rating: undefined out of 5
Keywords: laravel mistakes, Common mistakes in laravel, bad coding habit, laravel mistakes by developer, 8 developers mistakes, laravel developers, 8 laravel mistakes, laravel junior developer, laravel developers mistakes, How to Fix, how to fix laravel mistakes, laravel mistakes examples, laravel examples, 8 mistakes by laravel developers, laravel code mistakes, fix laravel code, how to fix laravel code, laravel tutorial, top laravel mistakes, laravel best practice, srp, laravel 10
Id: Pa119MuCPfI
Channel Id: undefined
Length: 23min 36sec (1416 seconds)
Published: Wed Mar 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.