Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where did Laravel get references() method?

I've been stucked for quite an hour now as I am trying to find out where did Laravel 5.2 get the references() method code is shown below

Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('title');
        $table->text('body');
        $table->text('excerpt')->nullable();
        $table->timestamps();
        $table->timestamp('published_at');

        $table->foreign('user_id')->references('id')->on('users');
});

I can't seem to find the references() method in either \Illuminate\Database\Schema\Blueprint or Illuminate\Support\Fluent.

can anyone point me to where is the references() method in the above code can be found?

any help and tips would be great

like image 219
Reyn Avatar asked Feb 08 '23 04:02

Reyn


2 Answers

Looks like it is handled by Fluent through the __call magic method.

Laravel API - Fluent @__call

Any method call that doesn't exist (or is inaccessible) will get passed to __call which will set an attribute, named by the method, to the value you have passed.

Example

$f = new \Illuminate\Support\Fluent;
$f->something('value')->willBeTrue();

dump($f);
//
Illuminate\Support\Fluent {
  #attributes: array:2 [
    "something" => "value"
    "willBeTrue" => true
  ]
}
like image 55
lagbox Avatar answered Feb 11 '23 01:02

lagbox


I found the same thing as lagbox when I cracked open the Blueprint class and saw that it was using the Fluent which implements several contracts among which Arrayable and Jsonable, and indeed any non existing method will get passed to the __call method and it will create a new element in the attributes array with the key as the method name:

$this->attributes[$method] = count($parameters) > 0 ? $parameters[0] : true;

But I would still extend this question: where does it really make use of that property when creating a foreign key constraint on the database record? I know it won't be really useful to go that deep, but I found myself really curious about how the Schema builder works beyond catching those methods.

Another good mention would be triggers like onDelete('cascade') that are normally used in this kind of situations.

like image 37
Cristian F. Avatar answered Feb 10 '23 23:02

Cristian F.