LARAVEL ERROR。未定义的变量:用户

时间:2018-04-06 14:36:54

标签: php laravel eloquent

我需要帮助

我搜索了很多,但我没有找到解决方案。我无法从Controller传递变量来查看

我在web.php中的路线

Route::get('admin/all','PolicyController@index');

我的控制器PolicyController.php

    <?php

namespace App\Http\Controllers;


use App\Policy;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


class PolicyController extends Controller
{

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
      public function index()
       {
         $users = User::all();
        return view('admin.all',compact('users'));   
         }
      }

我的观点是all.blade.php

@if($users)
   <div class="alert alert-warning"><strong>Sorry!</strong> No user Found. 
    </div>   

   @else
   @foreach($users as $user)
     <tr role="row">
       <td>
          <a href="{{ route('edit', $user->id) }}">{{ $user->name }}</a> 
       </td>
     <td>{{ $user->email }}</td>
       <td></td>
     <td><span class="label label-success"><span class="label label-success">{{ $user->status }}</span></td>
            </tr>
     @endforeach
    @endif

我认为问题出在Controller中,因为$ users是空的。但我不知道问题出在哪里......

祝你好运

4 个答案:

答案 0 :(得分:0)

您可以尝试使用with();代替

return view('admin.all')->with('users', $users);

答案 1 :(得分:0)

PolicyController.php替换

return view('admin.all',compact('users'));

return view('admin.all', ['users' => $users]);

答案 2 :(得分:0)

只需在刀片中使用isset()

替换&#34; @if($ users)&#34; @if(isset($ users)&amp;&amp; count($ users))

答案 3 :(得分:0)

可能是HomeController的问题,PolicyController中的每一件事似乎都可以。 你可以尝试:

public function index()
    {
       if (\Auth::user()->admin == 1)
          $users = User:all();
          return view('admin.all', compact('users));

       $policies = Policy::where('user_id', auth()->user()->id)->get();
          return view('staff',compact('policies'));
    }