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:
- 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;
}
}
- 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();
});
- 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.
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.
Random Code Snippet Queries: Laravel
- How to get random string in Laravel
- How to get images from AWS s3 and display in Laravel blade
- RuntimeException You must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
- Use withCount() to Calculate Child Relationship Records
- If no route matched route::fallback in laravel
- Symlink(): No such file or directory
- Permanently delete a record in laravel
- Validation errors for multiple forms on same page Laravel
- How to get route name on visit URL in laravel
- Display first n record from collection in laravel view
- SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
- Insert dummy data in users table Laravel
- How to get all posts which contains comments in laravel
- How to send email in laravel
- Generate random string lowercase in Laravel
- Laravel insert query not working
- How to get path from current URL in Laravel
- The POST method is not supported for this route. Supported methods: PUT.
- How to get tomorrow and yesterday date in laravel
- Laravel hasmany select not working
- The use statement with non-compound name 'Auth' has no effect
- Laravel create default admin user
- Get current month records in laravel 7/8
- Get comma separated email from input array
- Laravel clone model