compact(): Undefined variable: operator

Viewed 50088

I'm getting the following error

  (1/1) ErrorException
  compact(): Undefined variable: operator

This is my line of code

$postsCat = Post::whereHas('Cat', function($query) use ($sreachWord) {
    return $query->whereRaw('name REGEXP"'.sql_text_to_regx($sreachWord).'"');
})->orderBy('top','desc')
->orderBy('updated_at','desc')
->paginate(30);

Why is this happening? Is it because of my PHP version (7.3) or something else?

7 Answers

Go to your project in

vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php

On line number 1337, you can found below code inside the addWhereExistsQuery method

$this->wheres[] = compact('type', 'operator', 'query', 'boolean');

You just remove the 'operator' parameter.

And I hope it will work fine.

There are 2 fixes for this issue

  1. Downgrade your php to 7.2
  2. run "composer update" as in latest Laravel this issue has been resolved.

Instead of passing the variable to the compact() method, you'll passe it the name of the variable as a string without the dollar symbol.

$postsCats = Post::all(); // example

return view('posts.index', compact('postsCats'));

If you are not able to upgrade your Laravel, you just could change your Query to RAW query, it worked for me.

  $posts = Post::latest()->get();
            return view('author.post.index', compact('posts'));

Latest PHP version doesn't allow use of undefined variables. Instead of removing the latest version, another option is to switch between versions. Install earlier version say PHP7.2 as outlined here. Then set this as the preferred version by running sudo update-alternatives --set php /usr/bin/php7.2 on your Ubuntu terminal. Then run composer update

Related