Laravel 中未显示的部门

Posted

技术标签:

【中文标题】Laravel 中未显示的部门【英文标题】:Departments not showing in Laravel 【发布时间】:2020-05-30 21:19:47 【问题描述】:

我有两个表,部门和用户。一个部门有很多用户。一个用户属于一个部门。我正在尝试编写一个 foreach 循环来显示部门名称及其用户,但我收到此错误。


Facade\Ignition\Exceptions\ViewException 未定义变量:部门(查看:C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php

创建用户表


    public function up()
    
        Schema::create('users', function (Blueprint $table) 
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        );
    

创建部门表

public function up()
    
        Schema::create('departments', function (Blueprint $table) 
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        );
    

部门.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model


    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()

    return $this->belongsTo(Department::class);




用户.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable


    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    
        return $this->belongsTo(Department::class);
    


dashboard.blade.php

 @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content') 

<div class="row">
  <div class="col-md-12">
    <div class="card">
      @if (session('status'))
      <div class="alert alert-success" role="alert">
         session('status') 
      </div>
      @endif
      <div class="card-header">
        <h4 class="card-title"> DASHBOARD </h4>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <thead class=" text-primary">
              <th>ID</th>
              <th>Name</th>
              <th>Last Name</th>
              <th>Department</th>
            </thead>
            <tbody>
            @foreach($departments as $department)
              <td> $department->name</td>
              @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>


  @endsection

  @section('scripts')

  @endsection 

DashboardController.php

class DashboardController extends Controller
  public function index()
    
      $users= User::all();
      foreach($users as $user)
      
        echo $user->department->name;
        echo $user->name;
      
   

web.php


Route::get('/', function () 
    return view('welcome');
);


Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');


Route::group(['middleware' => ['auth','admin']], function  () 

    Route::get('/dashboard', function () 
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users')); 
    );
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboardid', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/id', 'Admin\DashboardController@registeredit');   
    Route::put('/role-register-update/id', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/id', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');


    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/id', 'Admin\DepartmentController@edit');
    Route::put('/department-update/id', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/id', 'Admin\DepartmentController@delete');


);
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

我也试过了,但还是一样。

<td> $department->name</td>

@foreach($departments->name as $department)
<td> $department</td>
@endforeach

【问题讨论】:

您似乎修改了代码。这是控制器中导致特定错误的代码 是的,我做了一些更改,但是这个 foreach 部分给了我这个错误 $department 请显示用户和部门的模型,因为我认为您可能没有设置它们之间的关系。 我现在在问题部分添加了 很难判断您现在拥有的代码何时会产生不同的结果。有些事情要注意。首先只得到 1 个值,所以你不能 foreach 循环它,如果查询以任何方式失败,那么 $departments 将为 null 或 false 不是未定义 【参考方案1】:

你可以试试这个吗?看看它是否改变了错误?


use App\User;
use App\Department;

Route::get('/dashboard', function () 
    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users')); 
);

注释掉这个。

// Route::get('/dashboard', 'Admin\DashboardController@index' );

此外,在您的 balde 文件中,您需要对此进行修改,这将为您提供所有部门。

              @foreach($departments as $department)
              <td> $department->name</td>
              @endforeach

更新

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model


    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function users()

    return $this->belongsTo(User::class);



【讨论】:

评论不用于扩展讨论;这个对话是moved to chat。【参考方案2】:

在您的 web.php 中, 替换这个:

Route::get('/dashboard', function () 
    return view('admin.dashboard');
);

用这个:

Route::get('/dashboard', 'Admin\DashboardController@index' );

在你的仪表板控制器中,替换这个:

public function index()

    $users= User::all();
    $departments = Department::with('users')->first();
   // return view('admin.dashboard')->with('departments',$departments)->with('users',$users); 
    // $departments = Department::with('users')->where('users.department_id','=','departments.id')->first();
    // dd($departments);
     dd($users); 
    // return view('admin.dashboard',compact('departments','users'));        

用这个:

public function index()

    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users'));        

【讨论】:

InvalidArgumentException 视图 [Admin\DashboardController@index] 未找到。我通过这些更改得到了这个 @klearn 首先,我看到您在 web.php 中多次定义了 get('/dashboard' ... 。请确保不是。 我用 get('/dashboard... in web.php ) 评论了这些部分,但又出现了同样的错误【参考方案3】:
Route::get('/dashboard', function () 
    return view('admin.dashboard');
);

这是你的问题。您将返回仪表板视图而不将部门列表传递给它。

这条路线应该使用DashboardController@index(并且您的注释代码应该取消注释) - 它获取部门列表并在传递列表时返回视图。

如果您使用 URL /departments 和 DepartmentsController 会更好...

【讨论】:

【参考方案4】:

尝试将User 模型更改为具有以下关系:

public function department()

    return $this->belongsTo(Department::class);

在 DashboardController 中将其更改为以下内容:

class DashboardController extends Controller

   public function index()
   
     $users= User::all();
     foreach($users as $user)
     
       echo $user->department->name;
       echo $user->name;
     
  

并更新相关路由:

Route::get('/dashboard', "Admin\DashboardController@index");

【讨论】:

ErrorException Trying to get property 'name' of non-object $user->department->first()->name dd($user) 并查看存在哪些数据而不是 echo 语句

以上是关于Laravel 中未显示的部门的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.3 中未显示 Passport 组件

在 Laravel 刀片中生成的 PDF 中未显示字体真棒图标

如果在 laravel 5.1 中未授权操作,则通过 ajax 显示错误

Laravel 7:foreach 循环中未定义的变量

laravel 5.5 中未设置分页样式

在 laravel 6.0 中未定义命令“ui”