Ad

How To Call Two Model Method In My Controller In Laravel

I hope you can understand the question, the fact is that I have created two methods in my model, one used to filter records by category and the other by city.

But when I go to my controller, in the public function index, I think it can't call both at the same time, I hope it is better understood in the example.

public function **scopeBuscadorCategoria** (Builder $query) {
    if (session()->has('s')){
        $query->where('nombre', 'LIKE', "%". session('s') ."%");
    }
    if (session()->has('dcategoria')){
        $query->where('categoria_id', session('dcategoria'));
        session()->remove('dcategoria');
    }
    return $query->paginate();
}

public function **scopeBuscadorLocalidad** (Builder $query) {
    if (session()->has('dlocalidad')){
        $query->where('localidad_id', session('dlocalidad'));
        session()->remove('dlocalidad');
    }
    return $query->paginate(21);
}

As you can see, those are the two methods that I have created in the model.

public function index (){
    **$destinos = Destino::buscadorcategoria();**
    $categorias = Categoria::paginate(6);
    $localidades = Localidad::all();
    return view('destinos.index', compact('destinos', 'categorias', 'localidades'));
}

And I think here is the problem, in the controller, "$destinos = Destino::buscadorcategoria();", I can only put 1 method, in this case it filters records of the categories, but if I need to filter by city, I must delete the method of categories and put the city, something like "$destinos = Destino::buscadorlocalidad();"

Can you call two methods in the variable $destinos? What could you do in this case? I need to filter by category and by city.

I hope you can help me, thank you all very much.

Ad

Answer

Your scopes shouldn't return "paginate" but only the query :

public function scopeBuscadorCategoria (Builder $query) {
    if (session()->has('s')){
        $query->where('nombre', 'LIKE', "%". session('s') ."%");
    }
    if (session()->has('dcategoria')){
        $query->where('categoria_id', session('dcategoria'));
        session()->remove('dcategoria');
    }
    return $query;
}

public function scopeBuscadorLocalidad (Builder $query) {
    if (session()->has('dlocalidad')){
        $query->where('localidad_id', session('dlocalidad'));
        session()->remove('dlocalidad');
    }
    return $query;
}

And in your controller :

public function index (){
    $destinos = Destino::buscadorcategoria()->buscadorLocalidad()->paginate(21);
    $categorias = Categoria::paginate(6);
    $localidades = Localidad::all();
    return view('destinos.index', compact('destinos', 'categorias', 'localidades'));
}
Ad
source: stackoverflow.com
Ad