How to get current model from user method in laravel

I'm not sure I'm asking the right questions, but this is what I'm trying to do.

So we can get current from

$model = Model::find($id)

Then we can get relationships such as:

$model->relationships()->id

Then we have such actions as:

$model->relationships()->detach(4);

My question is: can we create our own method:

$model->relationships()->customMethod($params);

and in the model it might look like this:

  public function customMethod($params){ //Do something with relationship id } 

But more than that, how customMethod I get $models information as id in customMethod ?

Sorry if this can be a bit confusing.

+6
source share
1 answer

First of all , if you want to access a related object, you do this by accessing an attribute with the same name as the relation. In your case, in order to access objects (objects) from relationships , you need to do this:

 $model->relationships //returns related object or collection of objects 

instead

 $model->relationships() //returns relation definition 

Secondly , if you want to access the attributes of a related object, you can do it like this:

 $relatedObjectName = $model->relationship->name; // this works if you have a single object on the other end of relations 

Finally, if you want to call a method in a related model, you need to implement this method in the corresponding model class.

 class A extends Eloquent { public function b() { return $this->belongsTo('Some\Namespace\B'); } public function cs() { return $this->hasMany('Some\Namespace\C'); } } class B extends Eloquent { public function printId() { echo $this->id; } } class C extends Eloquent { public function printId() { echo $this->id; } } $a = A::find(5); $a->b->printId(); //call method on related object foreach ($a->cs as $c) { //iterate the collection $c->printId(); //call method on related object } 

You can learn more about how to define and use relationships here: http://laravel.com/docs/5.1/eloquent-relationships

+2
source

All Articles