Blog Detail

04

Feb
10 Latest Tips about Laravel that you should know in 2022 cover image

arrow_back 10 Latest Tips about Laravel that you should know in 2022

Laravel has been the Best framework of PHP for many years. It has a massive ecosystem, active community, strong job market, successful startups, MVC architecture support, the creative template engine, etc. It has everything that makes it beneficial to adopt new technology. Laravel also helps website developers simplify their development process with clean and reusable code. In this blog, I’ve collected some awesome tips and tricks related to Laravel that can assist you in upgrading your code and app performance.

The findOrFail method also accepts a list of ids

The findOrFail method also accepts a list of ids. If any of these ids are not found, then it fails.
Nice if you need to retrieve a specific set of models and don’t want to have to check that the count you got was the count you expected

User::create(['id' => 1]);
User::create(['id' => 2);
User::create(['id' => 3]);

// Retrives the user...
$user = User::findOrFail(1);

// Throws a 404 because the user doesn't exist...
User::findOrFail(99);

// Retrives all 3 users...
$users = User::findOrFail([1, 2, 3]);

// Throws because it is unable to find *all* of the users
User::findOrFail([1, 2, 3, 99]);

Get a single column’s value from the first result

You can use the value() method to get a single column’s value from the first result of a query.

// Instead of
Integration::where('name', 'foo')->first()->active;

// You can use
Integration::where('name', 'foo')->value('active');

// or this to throw an exception if no records found
Integration::where('name', 'foo')->valueOrFail('active')';

Check if the altered value changed key

Ever wanted to know if the changes you’ve made to a model have altered the value for a key? No problem, simply reach for originalIsEquivalent.

$user = User::first(); // ['name' => "John']

$user->name = 'John';

$user->originalIsEquivalent('name'); // true

$user->name = 'David'; // Set directly
$user->fill(['name' => 'David']); // Or set via fill

$user->originalIsEquivalent('name'); // false

Remove several global scopes from the query

When using Eloquent Global Scopes, you not only can use MULTIPLE scopes but also remove certain scopes when you don’t need them, by providing the array without withoutGlobalScopes() Link to docs

// Remove all of the global scopes...
User::withoutGlobalScopes()->get();

// Remove some of the global scopes...
User::withoutGlobalScopes([
    FirstScope::class, SecondScope::class
])->get();

Order based on a related model’s average or the count

Did you ever need to order based on a related model’s average or count?
It’s easy with Eloquent!

public function bestBooks()
{
    Book::query()
        ->withAvg('ratings as average_rating', 'rating')
        ->orderByDesc('average_rating');
}

Retrieve the Query Builder after filtering the results

To retrieve the Query Builder after filtering the results: you can use ->toQuery().
The method internally uses the first model of the collection and a whereKey comparison on the Collection models.

// Retrieve all logged_in users
$loggedInUsers = User::where('logged_in', true)->get();

// Filter them using a Collection method or php filtering
$nthUsers = $loggedInUsers->nth(3);

// You can't do this on the collection
$nthUsers->update(/* ... */);

// But you can retrieve the Builder using ->toQuery()
if ($nthUsers->isNotEmpty()) {
    $nthUsers->toQuery()->update(/* ... */);
}

Checking For Table/Column Existence

You may check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable('users')) {
    // The "users" table exists...
}

if (Schema::hasColumn('users', 'email')) {
    // The "users" table exists and has an "email" column...
}

Use through instead of the map when using pagination

When you want to map paginated data and return only a subset of the fields, use through rather than map. The map breaks the pagination object and changes its identity. While through works on the paginated data itself

// Don't: Mapping paginated data
$employees = Employee::paginate(10)->map(fn ($employee) => [
    'id' => $employee->id,
    'name' => $employee->name
])

// Do: Mapping paginated data
$employees = Employee::paginate(10)->through(fn ($employee) => [
    'id' => $employee->id,
    'name' => $employee->name
])
$request->date() method

New Laravel v8.77: $request->date() method.

Now you don’t need to call Carbon manually, you can do something like:

$post->publish_at = $request->date('publish_at')->addHour()->startOfHour();

Link to full pr by @DarkGhostHunter

Get value from the session and forget

If you need to grab something from the Laravel session, then forget it immediately, consider using session()->pull($value). It completes both steps for you.

// Before
$path = session()->get('before-github-redirect', '/components');

session()->forget('before-github-redirect');

return redirect($path);

// After
return redirect(session()->pull('before-github-redirect', '/components'))

Closing Notes

These are some useful tips and tricks related to the Laravel framework, I hope that by following these tips you will improve the performance of your code and usability.

If you are a business and want to leverage Laravel for your next PHP-based website development or web application development for your bespoke requirements, you must discover an impeccable team with proficiency in the Laravel framework. So Codebrisk is here to help you with your tailored requirements regarding Laravel Development.

Want to chat with us? Please feel free to send us an email at rizwan@codebrisk.com or get in touch with us, our business person will get back to you.

Published at : 04-02-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project