Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel Higher Order Messages Code Examples

Get to know Laravel higher-order messages with code examples

Created on Oct 25, 2021

12 views

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

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

)