Home > OS >  Array on where clause laravel
Array on where clause laravel

Time:10-17

I have an array of values I want to pass into my where clause when querying a model

How do I achieve this?

I have $categorypro variable getting below array in this format

Array
(
    [0] => 4
    [1] => 8
    [1] => 5
)

Currently I am doing this in controller but not getting proper data some category

Below is my controller code :

function filter_each_video(Request $request){
        if(request()->ajax()){
if($request->has('categorypro') && ($request->get('categorypro')!= null)){
                $categorypro = $request->get('categorypro');
                $item = Item::whereIn('category_id', $categorypro)->get();
            }
}
}

If any one have better idea then let me know . Or something wrong in this then give some idea

CodePudding user response:

Generally you would use a 'whereIn' clause:

 MyModel::whereIn('attribute', ['value', 'value', 'value'])
        ->get();

CodePudding user response:

First, you already have the $request in your method, so you don't need to call request(). Always make sure you're validating any data you're using from a request. Second, you can get the query first, then filter it if necessary depending on the post data. Only put your whereIn filter inside the if block.

public function filter_each_video(Request $request)
{
    $request->validate([
        'categorypro'   => 'nullable|array',
        'categorypro.*' => 'int'
    ]);

    $query = Item::query();

    if ($request->ajax() && $request->categorypro) {
        $query->whereIn('category_id',$request->categorypro);
    }

    $categories = $request->categorypro 
        ? Category::whereIn('id',$request->categorypro)->get()
        : null;

    $items = $query->get();

    return view('myview',compact('items'));
}
  • Related