Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current model from custom method in laravel

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

So we can get the current from

$model = Model::find($id)

Then we can get it's relationships like:

$model->relationships()->id

Then we have actions like:

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

My question is, can we have a custom method like:

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

and in the model it may look like:

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

But further more, how in the customMethod would I get the $models info like id?

Sorry if this may be a bit confusing.

like image 1000
Jason Spick Avatar asked Aug 13 '15 12:08

Jason Spick


Video Answer


1 Answers

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 object(s) from relationships, you need to do this by:

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

instead of

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

Secondly, if you want to access attributes on the related object, you can do it the same way:

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

Lastly, if you want to call a method on a related model you need to implement this method in related 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 read more about how to define and use relationships here: http://laravel.com/docs/5.1/eloquent-relationships

like image 178
jedrzej.kurylo Avatar answered Oct 20 '22 17:10

jedrzej.kurylo