Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel undefined variable inside a function

I get my $id from the url, but I couldn't find a way to use it in a function. How can I pass $id to the query function?

I tried global $id but I still can't get a value, just empty page.

My controller.

class BookController extends Controller
{
    public function bookIndex($id, $slug)
    {
     // echo $id works without a problem
     $findcover = Thing::with(array('cover' => function($query) {
                $query->where('imageable_type', 'App\Models\Thing')
                  ->where('imageable_id', $id);
            }))->find($id);

            $maincover = $findcover->cover;
}

Error:

ErrorException in BookController.php line 49:
Undefined variable: id

Line 49

->where('imageable_id', $id);
like image 744
salep Avatar asked Sep 12 '15 00:09

salep


1 Answers

class BookController extends Controller
{
   public function bookIndex($id, $slug) {
   // echo $id works without a problem

   $findcover = Thing::with(array('cover' => function($query) use ($id) {
        $query->where('imageable_type', 'App\Models\Thing')
              ->where('imageable_id', $id);
        }))->find($id);

        $maincover = $findcover->cover;
   }

Add the reserve word use to insert your $id along your query.

like image 51
aldrin27 Avatar answered Nov 13 '22 01:11

aldrin27