【问题标题】:Laravel undefined variable inside a functionLaravel函数内未定义的变量
【发布时间】:2015-09-12 00:45:55
【问题描述】:

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

我尝试了 global $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;
}

错误:

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

第 49 行

->where('imageable_id', $id);

【问题讨论】:

  • function($query) use $id?
  • 是的,我需要在我的函数中使用那个 $id。
  • 我的意思是在您的查询中插入它
  • 我不能将多个参数传递给该函数,它只接受一个参数。
  • 将您的查询更改为Thing::with('cover' => function($query) use $id { });'

标签: php eloquent laravel-5.1


【解决方案1】:
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;
   }

添加保留字use,以便在查询中插入您的$id

【讨论】:

  • 这对我来说非常接近。我只需要将$id 变量放在括号use ($id) 中。
  • $id 应该在括号中
猜你喜欢
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
相关资源
最近更新 更多