【问题标题】:Laravel: i can't send more then 2 variables from controller to a viewLaravel:我不能将超过 2 个变量从控制器发送到视图
【发布时间】:2018-01-04 18:08:06
【问题描述】:

所以我试图从控制器向视图发送一些查询,但是当尝试使用第三个变量时它说:

未定义变量:type(View:)

我在控制器中使用的代码是这样的:

    $doc=DB::table('documents')
        ->join('users', 'users.id', '=', 'documents.id_user')
        ->join('type_docs', 'type_docs.id', '=', 'documents.id_tipo_doc')
        ->join('departments', 'departments.id', '=', 'documents.id_departamento')
        ->select('documents.*', 'type_docs.type', 'users.name','departments.abbreviation')
        ->get();
  $user=DB::table('users')
  ->select('users.*')
  ->get();
  $type=DB::table('type_docs')
  ->select('type_docs.*')
  ->get();


        //$doc = Document::all();
  return view('dashboard',['doc'=>$doc],['user'=>$user],['type'=>$type]);

在视图中:

       @foreach($type as $types)
                  <option value="{{$types->id}}">{{$types->type}}</option>
       @endforeach

【问题讨论】:

  • 请重新阅读手册。

标签: php laravel laravel-5


【解决方案1】:

你应该返回一个数组:

return view('dashboard',['doc'=>$doc,'user'=>$user,'type'=>$type]);

我们还有其他方法:

return view('dashboard', array('doc'=>$doc,'user'=>$user,'type'=>$type));

return view('dashboard', compact('doc','user','type'));

return view('dashboard')
            ->with('doc', $doc)
            ->with('user', $user)
            ->with('type', $type);

return view('dashboard')            //using laravel Magic method.
            ->withDoc($doc)
            ->withUser($user)
            ->withType($type);

【讨论】:

  • return view('dashboard', compact('doc','user','type')); 应该是数组return view('dashboard', compact( ['doc', 'user', 'type'] ));
  • @ВилиславВенков 根据doc ==> compact() 采用可变数量的参数。每个参数可以是包含变量名称的字符串,也可以是变量名称数组。数组中可以包含其他变量名数组; compact() 递归处理它。
  • @Maraboc,对不起,我的错误。
  • @ВилиславВенков 没关系,我们都犯了错误,我们从中吸取教训;)
猜你喜欢
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 2014-12-08
  • 1970-01-01
  • 2016-12-02
相关资源
最近更新 更多