Juliver Galleto
Juliver Galleto

Reputation: 9047

returns 'undefined variable' even the variable is exist

I'm trying to do something like a auto suggestion, see below codes.

//search suggestion base on the string criteria given
public function search_tag(Request $request){
    $tags = tags::where(function($query){
        foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192
            $query->orWhere('tag_id','!=',$i->tag_id);
        }
    })->where('tag_name','LIKE','%'.$request->ss.'%')->get();

    return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]);

}

but it throws me this error

ErrorException in ItemsController.php line 192: Undefined variable: request

As you can see there is a '$request' variable

public function search_tag(Request $request){

but why it tells me that 'request' variable is undefined? any ideas, help please?

Upvotes: 1

Views: 221

Answers (4)

Vikash
Vikash

Reputation: 3561

In closure if you want to use variable then you have to write within use().

$tags = tags::where(function($query) use ($request){
    foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192
        $query->orWhere('tag_id','!=',$i->tag_id);
    }
})->where('tag_name','LIKE','%'.$request->ss.'%')->get();

Upvotes: 1

KiwiJuicer
KiwiJuicer

Reputation: 1972

It's a closure and the request is not known in this scope, try following:

    //search suggestion base on the string criteria given
    public function search_tag(Request $request) use ($request){
        $tags = tags::where(function($query) use {
            foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192
                $query->orWhere('tag_id','!=',$i->tag_id);
            }
        })->where('tag_name','LIKE','%'.$request->ss.'%')->get();

        return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]);

}

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163948

Pass the $request variable into the closure:

where(function($query) use ($request) {

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

http://php.net/manual/en/functions.anonymous.php

Upvotes: 1

CodingFreak
CodingFreak

Reputation: 102

In where closure you're using $request which is not available, so you need to pass $request via use method

public function search_tag(Request $request){
    $tags = tags::where(function($query) use ($request) {
        foreach(item_tags::where('item_id',$request->item_id)->get() as $i){ //this is the line 192
            $query->orWhere('tag_id','!=',$i->tag_id);
        }
    })->where('tag_name','LIKE','%'.$request->ss.'%')->get();

    return response()->json([ 'success' => true, 'tags' => $tags, 'ss' => $request->ss ]);

}

Upvotes: 2

Related Questions