Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting array of related IDs from a belongsToMany relation - Laravel 5.4

I had this solution working well in Laravel 5.3

$procedure = Procedure::findOrFail($id);
$attached_stages = $procedure->stages()->getRelatedIds()->toArray();

In my Procedure model:

public function stages()
{

    return $this->belongsToMany('App\Models\Stage', 'procedure_stage', 'procedure_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}

Now, after migrating to Laravel 5.4, I get this error:

Call to undefined method Illuminate\Database\Query\Builder::getRelatedIds()

Seems that the getRelatedIds has been removed.

My question:

how to get the array in 5.4?

Thank you in advance.

like image 304
Peter Avatar asked Feb 05 '17 14:02

Peter


2 Answers

It was removed(basically, changed the name, nothing more) from 5.4, but you have it in another name as i looked deep inside the belongToMany.php file. Use this And it should work very nicely.

$attached_stages = $procedure->stages()->allRelatedIds()->toArray();

Hope this help you, and other who will face that problem in the future and look in this post.

like image 152
GabMic Avatar answered Nov 03 '22 01:11

GabMic


to get ids array you can use pluck function

$procedure->stages()->pluck('stages.id')->toArray();
like image 34
Ordidaad Avatar answered Nov 03 '22 00:11

Ordidaad