0

I sent an array, but not working. What I'im doing wrong? I'm getting this error.

HTML:

<select name="category[]" class="js-example-basic-single form-control" multiple>
    @foreach ($category as $element)
        <option  value="{{ $element->name }}">
            {{ $element->name }}
        </option>
    @endforeach
</select>

Controller

public function index(Request $request)
{
    if(isset($request['category'])  && $request['category']){
        $search = $request['category'];
        $posts->whereHas('category', function($query) use($search) {
            $query->whereIn('name','like', $search);
        });
    }
}

Model post

public function category()
{
    return $this->belongsToMany('App\Models\Category','posts_categories','post_id','category_id');
}

Don't Panic
  • 13,965
  • 5
  • 32
  • 51
Phú
  • 25
  • 6
  • Voting to close as duplicate: [laravel querybuilder how to use like in wherein function](https://stackoverflow.com/questions/34329886/laravel-querybuilder-how-to-use-like-in-wherein-function). Question is also a syntax error, but the solution provided below only solves half the issue. – Tim Lewis Nov 21 '20 at 05:22

1 Answers1

1

The second parameter of the method is for your array. You are passing a string with 'like'.

https://laravel.com/docs/8.x/queries#additional-where-clauses

/**
* Add a "where in" clause to the query.
*
* @param  string  $column
* @param  mixed  $values
* @param  string  $boolean
* @param  bool  $not
* @return $this
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)

You want:

 $query->whereIn('name', $search);

Edited to remove LIKE from whereIn.

mikeroq
  • 252
  • 2
  • 7
  • 1
    Passing `'LIKE'` as the 3rd argument doesn't work... `$boolean = 'and'` is valid for `and` and `or`, not `LIKE`. A `WHERE IN ...` doesn't actually work with `like`. See the answers here: https://stackoverflow.com/questions/34329886/laravel-querybuilder-how-to-use-like-in-wherein-function. They'll have to use multiple `where()` and `orWhere()` clauses to handle this. – Tim Lewis Nov 21 '20 at 05:18