0

In laravel tutorial it's said that we can pass an array of conditions in where function. My question is when I pass an array of conditions previously made by me it doesn't work.

Here is the code in documentation:

$users = DB::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();

My code is:

$fields = collect($request->input());
    if($fields->has('data')){
        $fields = collect($fields->get('data'));
        $conditions = collect([]);
        if($fields->has('likes')){
            $fieldsL = $fields->get('likes');
            $conditions->push(['likes', $fieldsL]);
        }
        if($fields->has('title')){
            $fieldsT = $fields->get('title');
            $conditions->push(['title', $fieldsT]);
        }
        $data = DB::table('posts')->select('*')->where($conditions)-

>get();
        }

My error message:

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '[]' in 'where clause' (SQL: select * from `posts` where `[]` is null) in file D:\laravel\lara-api\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 68

PLEASE let me know if it's impossible. thanks.

  • 1
    @TimLewis I added the error message – Arifur Rahman Arif Jun 10 '21 at 18:06
  • Much better :) To answer your question, it _is_ possible, but there's something wrong with `$conditions` as you're constructing it. Can you [edit your question](https://stackoverflow.com/posts/67926094/edit) and add the output of `dd($conditions)`? – Tim Lewis Jun 10 '21 at 18:07
  • @TimLewis If I use return dd($conditions); in controller then I get Illuminate\Support\Collection {#1196 #items: [] } – Arifur Rahman Arif Jun 10 '21 at 18:13
  • That means you're passing an empty `Collection` to `->where()`, and that doesn't work. `Model::where(collect([]))->first()` throws that error. If you do `->where($conditions->toArray())`, it won't throw an error, and will return everything. Apparently, `where()` doesn't seem to like `Collection`s. – Tim Lewis Jun 10 '21 at 18:16
  • @ArifurRahmanArif It's better to use laravel eloquent for collect your posts. Would you like to use that? – Mohammad Hosseini Jun 10 '21 at 18:19
  • @MohammadHosseini That's irrelevant to this post. `DB::table('posts')->where($conditions)` and `Post::where($conditions)` would have the same issue here. – Tim Lewis Jun 10 '21 at 18:24
  • @TimLewis Thanks. It works – Arifur Rahman Arif Jun 10 '21 at 18:26
  • @TimLewis Is there a better way to do the work? Please let me know – Arifur Rahman Arif Jun 10 '21 at 18:31
  • This approach is fine, you just need to be aware of the difference between a `Collection` and an `array`. Alternatively, you could do `$query = DB::table('posts')->query();`, then in your `if()` statements, do `$query = $query->where(...);`, then at the end `$data = $query->get();`. – Tim Lewis Jun 10 '21 at 18:33

0 Answers0