Posts Learn Components Snippets Categories Tags Tools About

Laravel Higher Order Messages Code Examples

Get to know Laravel higher-order messages with code examples

Created on Oct 25, 2021


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.

use App\Models\Post;

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

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.

// 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.

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

// Higher Order Messages (very expressive)

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

Other reads

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

Load comments for Laravel Higher Order Messages Code Examples