TuGordoBello
TuGordoBello

Reputation: 4509

How I can filter a Collection in Laravel?

I have the follow code

$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();
        if($tecnico != ''){
            $servicios = $tecnico->servicios;
            $servicio = $servicios->where('idServicio', $id);
        }  

The Serviciohave many Tecnico and Tecnico have many Service

In this case I only need a Tecnico from a Auth_token later also need all Servicio from that Tecnico but filter by id When I run the above code the following error

Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to undefined method Illuminate\Database\Eloquent\Collection::where()

in $servicio = $servicios->where('idServicio', $id);

how can i fix it?

Upvotes: 3

Views: 653

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

Answer to your question is either:

// if idServicio is set as primary key on Servicio model
$servicio = $tecnico->servicios->find($id); 


// in case idServicio was just a property and not necessarily unique do this:
// it return Collection of Servicio models matching $id
$servicio = $recnico->servicios->filter(function ($servicio) use ($id) {
   return $servicio->idServicio == $id;
}); 

Anyway if you really need only that particular Servicio, use eager loading constraints like @WhereWolf suggested rather than filtering the collection.

Upvotes: 3

The Alpha
The Alpha

Reputation: 146191

You may try this:

$tecnico = Tecnico::with(array('servicios' => function($q) use ($id) {
    $q->where('idServicio', $id);
}))->where('Auth_Token',$auth)->firstOrFail();

So, you'll get the Tecnico model whose related Servicio->id is equal to $id, then you may use $tecnico->servicios->first() to get the first Servicio and if there are more than one Servicio (Most probably won't) in the collection then you may use a foreach loop (Basically in the view). You may check more about this aka Eager Load Constraints on the Laravel website.

Upvotes: 3

Related Questions