5 Laravel’s Hidden Gems

5-laravels-hidden-gems
Spread the love

1. Stop on first validation error

By default, Laravel will check for all validation rules and return a list of errors. But if you want to stop this process after first validation failure, that’s how you can achieve it

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

2. Find many

Most of us developers have used Eloquent’s method find to search for one specific id, but do you know we can pass multiple ids to find which will return a collection.

// Will return Eloquent Model
$user = User::find(1);
// Will return Eloquent Collection
$users = User::find([1,2,3]);

3. Relationship but with condition

Some times we need to apply where on relationships, instead of calling relationship and then chaining where we can achieve it by following:

// app/Post.php model
public function comments()
{
    return $this->hasMany(Comment::class);
}
public function approved_comments()
{
    return $this->hasMany(Comment::class)->where('approved', 1);
}

4. Rename pivotal table

In pivot table, if you want to rename pivot to some thing else, this can be done by following code:

public function podcasts() {
return $this->belongsToMany('App\Podcast')
->as('subscription')
->withTimestamps();
}
// Then somewhere in Controller...
$podcasts = $user->podcasts();
foreach ($podcasts as $podcast) {
// instead of $podcast->pivot->created_at ...
echo $podcast->subscription->created_at;
}

5. Prepare for validation

If you want to prepare a specific field before validation, you can do it by following code:

protected function prepareForValidation()
{
$this->merge([
'slug' => Illuminate\Support\Str::slug($this->slug),
]);
}