10 Latest Tips about Laravel that you should know in 2022
Tags: laravel, php, webdev, programming
Published: 2022-03-09 05:44:19

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 <code>key</code> ? No problem, simply reach for <code>originalIsEquivalent</code>.

```
$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 <code>withoutGlobalScopes()</code> 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 <code>use ->toQuery()</code>. The method internally uses the first model of the collection and a <code>whereKey</code> 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
```
### Get value from the session and forget

If you need to grab something from the Laravel session, then forget it immediately, consider using <code>session()->pull($value)</code>. 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'))
```

### 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();
```

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](https://codebrisk.com/blog/10-latest-tips-about-laravel-that-you-should-know-in-2022)


For More News & Updates, Follow me on [Twitter/iamSumyyaKhan](https://twitter.com/iamSumyyaKhan).