Levan Tetemadze
Levan Tetemadze

Reputation: 43

Laravel does not recognize $this->id when getting data in JSON

public function other_children(){ return $this->hasMany('App\SameModel', 'parent_id', 'parent_id') ->where('id','!=', $this->id); }

This works when I get data (query log: ... where id != ? ..., but when I return it in JSON like return SameModel::with('other_children')->first(); does not work. Query log: ... where id is not null ...

It does not recognize $this->id when getting data with ->with

Any solution?

Upvotes: 0

Views: 93

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25926

If you only have one model, you don't need to use eager loading:

$model = SameModel::first();
$model->other_children;
return $model;

Upvotes: 1

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can do it by nested like this

$id = $this->id;
return SameModel::with(['other_children' => function ($query) use($id) {
    $query->where('id','!=', $id);
}])->get();

In your question $this belongs to controller not to Model, this would be the reason to not recognizing $this->id in relation method which in model.

Upvotes: 0

Related Questions