Home / Snippets / Laravel Higher Order Messages Code Examples
Laravel Higher Order Messages Code Examples cover

Laravel Higher Order Messages Code Examples

176

3 years ago

0 comments

Laravel comes with several higher-order messages methods that are especially useful when performing short-cuts to do common Laravel actions. The collection methods that supports higher-order messages are:

How to use Higher Order Messages in Laravel?


To use higher order messages in Laravel you can chain any of the above methods like the code below. Do note that the main purpose of higher-order messages is to call each of the methods within the collection and perform the actions specified.
<?php

use App\Models\Post;

$posts = Post::where('views', '>', 500)->get();

$posts->each->markAsSpecial();
For the code example above we are getting all "posts" that have more than 500 views and for each of the records we will be "marking it as special" by calling the "markAsSpecial()" method.
<?php

// within the Post model you can define the code below

public function markAsSpecial()
{
    $this->update(['special' => true]);
}
For the comparison of the higher-order messages methods above vs normal collection method, do refer to the code below.
<?php

$users = User::query()->limit(100)->get();

// Higher Order Messages (very expressive)
$users->each->markAsSpecial();

// Normal / Common way (slightly more to write)
$users->each(function ($user) {
    $user->markAsSpecial();
});

Other reads

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this