2

Actually I am trying to know that how laravel is accepting multiple methods, suppose in laravel you can do something like below

Game::where('season_id', $timeSpanId)
->where('team_id', $whoId)
->where('stats_done', 'yes');
->get();

So in above script I can understand Game is a class and where can be a method. But in php we use method only once but in above script you can see in single line it can be use. And also look at get() method which is at the end of the script which would know that it need to fetch the record after execution of generated query.

Now suppose I have a class

Class Car{

    public function seat($param){
        return $param;
    }

    public function tyre($param){
        return $param;
    }

}

and I can use the methods as like below

$Car = new Car();
$Car->seat('Passenger Side');
$Car->tyre('Driver Side');

above script will return the result in proper way but I don't think that I can use as following

$Car->tyre('Driver Side')->seat('Passenger Side');

As far as I know that above script will throw an error, but that's I want to know that how laravel is doing that.

Can someone please give me idea of that logic of term that I can learn about it.

I am so sorry for question title, as I am not sure what it should be, you can help me by editing it.

Thank you so much.

Bram Verstraten
  • 1,414
  • 11
  • 24
Imran Abbas
  • 755
  • 1
  • 7
  • 24
  • 2
    The keyword you want to go read up on is _method chaining_. – misorude Aug 26 '19 at 08:22
  • 1
    To be able to chain calls like this, you need to do `return $this;` instead of `return $param;`. It means that you obviously can't do this for functions that should return a result. – Kaddath Aug 26 '19 at 08:25
  • 1
    Possible duplicate of [PHP method chaining?](https://stackoverflow.com/questions/3724112/php-method-chaining) – Bram Verstraten Aug 26 '19 at 08:29
  • You need to learn first about method chaining in php. using chain you can return full method instead of value using return $this inside method. – Ariful Islam Aug 26 '19 at 09:17
  • It's the laravel [fluent query builder](https://laravel.com/docs/5.8/queries#introduction), it's a way to construct a query with a "fluent" and expressive "language", almost all methods called return the instance of the query builder itself ($this) so you can chain methods. – dparoli Aug 26 '19 at 09:24

0 Answers0