Call query before yajra code in controller

18 Views Asked by At

I want to call query before yajra code begins in controller and use it in custom column of yajra code like this

//Query before code
$users = user::get();

if ($request->ajax() && $request->draw) {
    $data = table_name::get();
    return Datatables::of($data)
        ->addIndexColumn()
        ->addColumn('user', function($row){
        
            foreach($users as $item){
              //USE CODE DATA HERE
            }
        
            return $data;
        })
        ->rawColumns(['user'])
        ->make(true);
}

Like this it don't recognize $users variable. How can I achieve this?

1

There are 1 best solutions below

0
Alberto Moro On BEST ANSWER

To access the $users variable, you can use the use keyword to import the variable.

$users = user::get();

if ($request->ajax() && $request->draw) {
    $data = table_name::get();
    return Datatables::of($data)
        ->addIndexColumn()
        ->addColumn('user', function($row) use ($users){
            foreach($users as $item){
              //USE CODE DATA HERE
            }
            return $data;
        })
        ->rawColumns(['user'])
        ->make(true); }

If you want to learn more about using inherited variables from the parent scope, you can refer to the documentation here: Anonymous Functions - PHP Manual Example #3