Laravel - Useful Functions that not Everyone Knows
Laravel is a very extensive framework that gives the user many tools and opportunities to work on the project. Our Laravel developers learn something new every day when working for our clients. I decided to present to you today some less known, but very useful opportunities provided by the creators.
Apart from this article, consider checking also intuitiveness and quickness of writing the code.
1. Scheduler methods can be chained more
Performing recurring tasks is essential for most web application projects. Laravel meets this demand with its "Task Scheduling". This solution is made in a very extensive and friendly way.
// Every hour, on working days, between 8:00 and 17:00...
$schedule->command('foo')
-> weekdays()
-> hourly()
-> between('8:00', '17:00');
Any logically correct chainy of this type will work fine here. It is a very elegant and extremely comfortable solution.
It is also possible to create a more complex task in another class and delegate it to our command.
// Every hour, on business days, between 8:00 and 17:00, if shouldSkip() returns true...
$schedule->command('foo')
->weekdays()
->hourly()
->between('8:00', '17:00')
->skip(function () {
return app('SkipValidator')->shouldSkip();
});
These types of simplifications are a key part of the idea of this framework. You can read more about its uniqueness in our article comparing the Laravel vs Symfony - Major Differences.
2. Eloquent - find() method takes many parameters
The find() method can be used to retrieve more records. To achieve this, just pass an array as an argument. In this case, the method will return the collection of Eloquent models with the given id (of course if they exist). As simple and obvious as it may seem, I often come across code where someone has obviously forgotten it.
// Find a user with an id of 1.
$data = UserModel::find(1)
// Find users with id's 1, 2, 3, 4, 5.
$data = UserModel::find([1,2,3,4,5])
3. Query builder on several columns the easy way
Let's take an example SQL query here
SELECT
*
from
`users`
WHERE
`name` = 'developer'
AND `email` = '[email protected]'
LIMIT
1
Using Eloquent, we can simplify the query and present it as follows:
\App\User::whereNameAndEmail('developer','[email protected]')->first();
// The above example is a simplified version of the entries below.
\App\User::where('name', 'developer')->where('email', '[email protected]')->first();
\App\User::where(['name' => 'developer', 'email' => '[email protected]'])->first();
The solution works with both operators "and" and "or".
\App\User::whereNameOrEmail('developer','[email protected]')->first();
Once again, the intuitiveness and "simplicity" of the code written in Laravel are emphasized.
4. Attach files to email
Regardless of the tool we use, sending email messages with attachments and photos often turns out to be more complex and complicated than it should be. Laravel adheres to the KISS rule in this respect.
Let's assume that we want to attach to our message the file "secret_document_1.pdf", located under the path "/secrets_documents/secret_document_1.pdf".
Mail::send('emails.secret', [], function ($mail) {
$mail->to('[email protected]');
$mail->subject('Secret documents you asked for');
$mail->attach(public_path('secrets_documents/secret_document_1.pdf'));
});
The same applies to adding photos in the body of an email.
The photo you asked for:
<img src="{{ $message->embed(public_path('img/photo.jpg')) }}">
Thanks!
5. The original values of the attribute
After making changes to the Eloquent record, we are able to check its original value.
$user = App\User::first();
// The original value of the mail field -> [email protected]
$user->mail;
// We set a new value for this field.
$user->mail = '[email protected]';
// This field will now return its new value -> [email protected]
$user->mail;
// By using the getOriginal() method, we are able to get to the original value.
// In this case, it will return a value -> [email protected]
$user->getOriginal('mail');
// We are also able to download the entire original item.
$user->getOriginal();
6. Checking if the model has changed
As in the case of the previous point, we are able to determine if our facility has changed. A special isDirty() method has been prepared by the Laravel developers for this purpose. Let's expand our previous example with its implementation.
$user = App\User::first();
// The original value of the mail field -> [email protected]
$user->mail;
// The method will return 'false' because we are working on a freshly acquired object from the database.
$user->isDirty();
// We set a new value for this field.
$user->mail = '[email protected]';
// The method will return 'true' because we have just changed the value for the mail field
$user->isDirty();
// We can go a step further and check for changes for individual fields.
// It will return 'true'.
$user->isDirty('mail');
// It will return 'false'.
$user->isDirty('name');
// This field will now return its new value -> [email protected]
$user->mail;
// By using the getOriginal() method, we are able to get to the original value.
// In this case, it will return a value -> [email protected]
$user->getOriginal('mail');
// We are also able to download the entire original item.
$user->getOriginal();
Summary
Laravel is a very complex framework that gives developers a lot of freedom and possibilities. It also provides many functionalities that not everyone needs to know. The functions I present are only a fraction of all the possibilities that the system offers us and which we use every day in our PHP development agency.