Useful Tips and Tricks for Laravel
Laravel is one of the most widely used PHP frameworks in the world. Its simplicity, ease of use, and robust features have made it a popular choice for developers who want to create high-quality web applications with ease. However, even seasoned Laravel developers can sometimes struggle with certain aspects of the framework.
The Laravel tips and tricks tutorial covers a variety of advanced techniques for developers using the Laravel PHP framework to build more efficient and effective web applications. Let’s get started!
Make your code more elegant using Eloquent
Local query scopes
In our project, we have several conditions that need to be met. Consider this query, for example:
To achieve this, we can utilize Local Query Scopes to improve code readability and reduce repetition. As an example, we can create the following functions in our model:
Now, our original query would look like this:
2. Global query scopes
The global query scope allows you to apply a constraint to all queries on a model by default.
Let’s create a new global scope class.
Now, we will add scope to our model. So that when we use Eloquent ORM, it applies automatically.
Model boot() method
The static boot() method is automatically executed when a model is instantiated, making it an ideal location to add behavior or event bindings. In this case, setting the default value of the is_admin field during the creation of the model object is a suitable example. However, the sentence structure could be improved by breaking it into two or more sentences for better readability.
is() method in Laravel
Determines whether two models belong to the same table and share identical IDs.
Replicate a model
To replicate a model in Laravel, you can use the replicate() method, which creates a new instance of the model with the same details as the original. Additionally, you can modify any field values before saving the new instance to the database.
Select attributes in find() method
When using the find() method in Laravel, you can select specific attributes to retrieve by passing them as the second argument.
Expressive “where” Syntax
You can make this query more expressive like below, by suffixing the attribute to the where clause itself.
Model properties
There are some properties of an Eloquent model:
Override updated_at when saving
We can override the default updated_at behavior by telling the system to ignore the automatic timestamp feature and manually set the field to your desired value.
Here, we’re overriding the default updated_at with our pre-defined one.
Simple pagination
In pagination, if you need just “Previous/Next” links instead of all the page numbers (and have fewer DB queries because of that), simply change paginate() to simplePaginate().
Here’s an example of the same:
Laravel eloquent method
isDirty()
isClean()
wasChanged()
The “isDirty()” method determines if any attributes of a model have been changed when retrieved. We can also pass a single attribute to check if its value has been modified or not. Therefore, “isDirty()” method checks whether a model instance value has been changed. The method returns either false or true, where false means the value has changed, and true means the value has not been modified.
The “isClean()” method is the inverse of the “isDirty()” method. When the “isClean()” method is called, it returns “true” if none of the attributes of the model instance have been modified, and “false” if any attribute has been changed. For a clearer understanding of how the “isClean()” method works, please refer to the example below.
The “wasChanged()” method determines if after saving data any attribute value has changed. We pass a single attribute in the “wasChanged()” method. Example of “wasChanged()” method include:
Avoid using Environment (.env) variables directly
Environmental variables are a value that affects the way running processes behave in a computer. While you may be tempted to use them directly in your code, it’s best if you use the config() helper function to access them. Otherwise, external variables, like server-level or system-level environment variables, can easily override your .env file.
How to use View Composer
View Composer is used when multiple views require a certain variable or piece of data. For example, the following method could be written in any service provider’s bootmethod. This method attaches a users variable to every view.
Maintenance mode options
To put your app into maintenance mode, you can run the following command:
To refresh the maintenance page in set intervals when the site is up, run the following command:
To allow bypassing of maintenance mode using a secret token, you may use the secret option to specify a maintenance mode bypass token. This means that if you navigate to your-app-domain.com/your-secret-here, you will have access to view the rest of the application as normal.
To disable maintenance mode, use the up command:
Reuse or clone query
To query multiple times from a filtered query, we can use the query() method to reuse or clone the query. For example, let's write a query to retrieve all products that were created today, regardless of their status (active or inactive).
When we query a database for products, we often need to filter the results based on certain criteria. To achieve this, we create a $query object with the required conditions and then execute it to obtain a collection of products.
However, in some cases, we may need to query the database multiple times with different filter criteria. For example, we may need to retrieve all products created today, regardless of their status (active or inactive).
To accomplish this, we can use the $query object and modify it with the required conditions before executing it. However, this approach can cause issues when we need to retrieve products with different statuses using the same $query object.
For instance, when we obtain the $activeProducts collection, the $query object is modified to retrieve only active products. As a result, $inactiveProducts cannot find any inactive products from the $query object and returns an empty collection every time.
To solve this issue, we can reuse the same $query object by cloning it before modifying it for each query. By doing so, we can retrieve both active and inactive products without affecting the original $query object.
Model all columns
When calling Eloquent’s Model::all(), you can specify which columns to return.
DB transactions
When performing two database operations, if the second operation encounters an error, the first operation should be rolled back. To achieve this, we use database transactions. Transactions ensure that the first operation is automatically rolled back if the second operation fails.
Eager Loading with exact columns
You can use Laravel Eager Loading to retrieve related data along with the main query and specify the exact columns you want to get from the relationship. To optimize performance, you can specify the exact columns you want to retrieve from the related data, rather than retrieving all columns.
A shorter way to write whereHas
Released in Laravel 8.57, here’s a shorter way to write whereHas() with a simple condition inside.