Method chaining in Laravel

Created at 20-Jul-2023 , By samar

Method chaining in Laravel follows the same concept as method chaining in PHP.

To create method chaining in your own PHP class, you need to follow these steps:

  1. Define your class: Start by creating a class and defining the methods you want to chain. Each method should return the instance of the class ($this) to allow for chaining. Create a test directory in app folder of Laravel project and create a file Calculation.php in it add below code.

app\Test\Calculation.php

<?php
namespace App\Test;

class Calculation {

    public $result;


    public function __construct(){
        $this->result = 0;
    }

    public function add($num){
        $this->result += $num;
        return $this;
    }

    public function substract($num){
        $this->result -= $num;
        return $this;
    }

    public function multiply($num){
        $this->result *= $num;
        return $this;
    }

    public function getResult(){
        return $this->result;
    }

}
  1. Chain the methods: Within each method, you can call other methods on $this to chain them together. This allows you to invoke multiple methods in a single statement.

routes\web.php

use App\Test\Calculation;

Route::get('/method-chain', function(){
    return (new Calculation())->substract(10)->add(20)->multiply(5)->getResult();
});
  1. Now hit the url http://localhost:8000/method-chain in your browser. You will see the result.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.