Laravel未定义函数内的变量

sal*_*lep 9 php eloquent laravel-5.1

$id从网址获取了我,但我找不到在函数中使用它的方法.如何将$ id传递给查询函数?

我尝试了全局$ id,但我仍然无法得到一个值,只是空页.

我的控制器.

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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

ErrorException in BookController.php line 49:
Undefined variable: id
Run Code Online (Sandbox Code Playgroud)

第49行

->where('imageable_id', $id);
Run Code Online (Sandbox Code Playgroud)

ald*_*n27 14

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;
   }
Run Code Online (Sandbox Code Playgroud)

添加保留字使用以在您$id的查询中插入.

  • 这对我来说非常接近.我只需要将`$ id`变量放在括号`use($ id)`中. (3认同)