DEV Community

Cover image for 10 Latest Tips about Laravel that you should know in 2022
sumyya khan
sumyya khan

Posted on • Edited on

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]);
Enter fullscreen mode Exit fullscreen mode

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')';
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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(/* ... */);
}
Enter fullscreen mode Exit fullscreen mode

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...
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'))
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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.

For more details visit this link

For More News & Updates, Follow me on Twitter/iamSumyyaKhan.

Top comments (0)