Hion Coding - Blogs share everything
  • HOME
  • ABOUT
  • POSTS
  • CONTACT
  • TOOLS
    CÂU HỎI VÕ ĐÀI TỐI THƯỢNG CONVERT IMAGE TO WEBP
Elevating Junior Laravel Developers: Recipes & Best Practices

Elevating Junior Laravel Developers: Recipes & Best Practices

Hion Coding - Blogs share everything
Admin Hion Coding Blogs vochilong.work@gmail.com
3rd January 2024

PHP/Laravel

Elevating Junior Laravel Developers: Recipes & Best Practices

Reference: Viblo

About  Elevating Junior Laravel Developers series:

Index Elevating Junior Laravel Developers series:

  1. Elevating Junior Laravel Developers: Recipes & Best Practices
  2. Elevating Junior Laravel Developers: Learn about Service containers
  3. Elevating Junior Laravel Developers: Learn about Service Provider
  4. Elevating Junior Laravel Developers: Learn about Facade
  5. Elevating Junior Laravel Developers: Learn about Contract

Laravel is an Open-source PHP Web Application Framework, created by Taylor Otwell. Although it was born quite late when it only started in 2011, to date Laravel has become the most popular PHP Framework. The Laravel community is very active, and the number of packages for Laravel is also extremely large and diverse. Laravel completely surpasses other frameworks in terms of the number of stars or the number of forks on Github!
In this Elevating Junior Laravel Developers series, we aim to share insights into the fantastic world of Laravel and provide valuable tips for working on Laravel projects. Our hope is that you'll grow to appreciate and enjoy this excellent framework.

Recipes & Best Practices:

The N + 1 Problem and Eager Loading:

Let's say you have a problem like this:

  • You have a list of posts in the posts table, with an Eloquent Model named Post
  • Each Post belongs to one User. Post has a belongsTo relationship with User, and User has a hasMany relationship with Post.
  • You have a Post list page, which needs to display a list of Posts, of course with the author name of that post. This is a very common situation in projects, with many different variations. Below is a common solution.
// Post Model
public function user()
{
    return $this->belongsTo(User::class);
}
// In Controller or Somewhere else
$posts = Post::all();
// View
foreach ($posts as $post) {
    {{ $post->title }}
    {{ $post->user->name }}
}

So to print the name of the owner of the post, we used the user relationship that we defined, which means it will retrieve the User of the post's owner. If you install Laravel Debugbar then you will realize the problems with this method:

  • For each Post, we have to perform an SQL query to retrieve the User. If the number of your posts is large, the number of SQL queries that must be executed will also be large.
  • There is a possibility of making duplicate queries. For example, post numbers 1, 2, and 3 all belong to a user with an id of 1. In that case, we will have to perform 3 SQL queries with the goal of getting the user with an id of 1 (to assign to each post). post).

You should know that SQL queries are often one of the most time-consuming tasks in request processing. Obviously having to use so many queries is a problem we need to fix. We call that problem the N + 1 problem, because in addition to using 1 query to select N posts, you will have to use N queries to retrieve N users for those N posts.

Laravel provides a tool to solve this problem, which is Eager Loading.

// Eager Loading
$posts = Post::with('user')->all();

// Lazy Eager Loading
$posts = Post::all();
$posts->load('user');

By using the with() or load() function, we can load all Users belonging to all Posts at once with just one SQL query. This will help us reduce the number of queries significantly.

Always try to use Eager Loading whenever possible. Laravel provides us with a very perfect and powerful Eager Loading system. Besides loading one relationship as above, we can also load multiple relationships at once (Multiple Relationships Eager Loading), load overlapping relationships (Nested Eager Loading), or perform Eager Loading with conditions...
For detailed information on how to use Eager Loading you can see here Official Document của Laravel

 

Method or Property?

Continuing an issue related to Eloquent relations. Suppose you encounter a problem like this:

  • Each Category has many Posts. Each Post belongs to a Category.
  • You have a Category view page, and in the page showing detailed information about that category, you need to display the number of articles in the category. To solve the problem of getting the number of posts in a category, we have the following way.
// Category Model
public function posts()
{
    return $this->hasMany(Post::class);
}
// View. We can use
$category->posts->count();
// Or
$category->posts()->count();

As I wrote above, we have 2 ways to write: $category->posts->count(); and $category->posts()->count();. Do you know how different it is?

First, we need to know that $category->posts() is a call to the posts() function from the $category instance, while posts are a call to the property.

The way to call $category->posts() is as defined above: return $this->hasMany(Post::class);, we can see it will return an instance of Category. However, in Model Category there is no property called posts, so what will calling $category->posts return?

The answer is that Laravel uses PHP's Magic Methods to make calling the posts property valid. And it will return the result of the post's relation. That is, $category->posts here will be equivalent to $category->posts()->get(). A special thing about calling via a property is that Laravel will only query the DB the first time, receive the results, and will store the results in the newly created property.

Above we have a Category hasMany relationship with Posts, so $category->posts will return a Collection (Collection is a Class in Laravel that helps manage Arrays easily and more convenient).

So we can see how the two commands above work will be as follows:

  • $category->posts->count(): First $category->posts will query the DB to retrieve all posts belonging to the current category. The result is a Collection. Then the count() function is called on this Collection to count the number of elements of the Collection. It is as simple as the count() function that counts the number of elements in an array. That is, with this statement, we will retrieve all posts belonging to the category in the DB, and use PHP processing to count the number of posts. No matter how many times you call this command, the DB query will only be executed once, that is on the first call.
  • $category->posts()->count(): Initially $category->posts() will return $category instance provided the query is a posts relation. Then the count() function is used as an Eloquent function, with the task of building the count query in MySql, for example. That is, with this command, we will run only one DB query to count the number of posts records belonging to the category. Each time you call this command, you have to query the DB.

Once you understand the nature of the other two ways of calling, you will be able to consider for yourself which writing method you should use in which situation. For example, if you have a Category view page, which only needs to display the number of posts in the Category without paying attention to the content of the posts, it is clear how to call $category->posts()->count() is much more optimal. However, if you need to print posts as well, calling $category->posts->count() is better, because you need to call $category->posts to get the posts anyway, Then call the count function from there, which will help you avoid having to query the DB again.

 

Dependency Injection:

Dependency Injection is a design pattern commonly used in modern frameworks. Simply put, it means that if a Class A depends on several other Classes, then instead of creating instances of those Classes inside Class A, we will inject those instances through the constructor or setter. The instances of Classes that Class A needs to operate are called dependencies.

// Non Dependency Injection
Class A
{
    protected $classB;
    public function __construct()
    {
        $this->classB = new ClassB();
    }
}

// Dependency Injection
Class A
{
    protected $classB;
    public function __construct(ClassB $classB)
    {
        $this->classB = $classB;
    }
}

Within the framework of this article, I will not analyze the concept of Dependency Injection in depth, this is an important concept that you should learn and master. Instead, let's take a look at an effective way to use Dependency Injection in Laravel.

Laravel provides us with a powerful tool called Service Container. That's where Class Dependency is managed, which means seeing what dependent Classes a Class has. In addition, it also helps us perform Dependency Injection effectively through the class constructor. Laravel's Service Container can help you inject dependencies into many types of Classes, from Controllers, Event listeners, to Queue Jobs, Middleware, Console Command...
For example, we can inject the Mailer class into the Controller as follows:

<?php

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(Request $request, $id)
    {
        $all = $request->all();
    }
}

 

Repository Design Pattern:

Repository Design Pattern is currently a very popular method of working with Laravel projects. To put it simply, you will create a Repository layer between the Controller and Model (ORM Layer), with the task of implementing business logic to process the DB, thereby avoiding writing Business Logic in both Controller and Model. , creating functions that can be reused in many different places.
With the Repository Pattern, the Controller will no longer work directly with the Model, it needs to handle DB-related processing, and it will work with the Repository.

class CategoryController extends BaseController
{
    private $categoryRepository;

    public function __construct(CategoryRepository $categoryRepository)
    {
        $this->categoryRepository = $categoryRepository;
    }

    public function show($id)
    {
        $category = $this->categoryRepository->find($id);
    }
}

 

Conclusion:

In this post, we've explored several fundamental concepts and best practices in Laravel. We hope you find these insights valuable as you embark on your journey with Laravel. In future articles, we'll delve deeper into Laravel's core concepts and provide in-depth explanations of advanced topics like inversion of control, service providers, contracts, facades, middleware, jobs, and events.

Please continue exploring Laravel's rich ecosystem, and don't hesitate to consult the official Laravel documentation for further details on these topics.

Reference: Viblo

Thank you! Good luck! Hion Coding


Integrating CKEditor 5 In Laravel 10 Using Vite

9th April 2024

Integrating CKEditor 5 In Laravel 10 Using Vite

PHP/Laravel

Laravel Eloquent Tips🔥 🚀

3rd January 2024

Laravel Eloquent Tips🔥 🚀

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Contract

3rd January 2024

Elevating Junior Laravel Developers: Learn about Contract

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Service Provider

3rd January 2024

Elevating Junior Laravel Developers: Learn about Service Provider

PHP/Laravel

Hion Coding - Blogs share everything


© 2025 Hion Coding DMCA.com Protection Status