skip to Main Content

I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.


FacadeIgnitionExceptionsViewException
Undefined variable: departments (View: C:xampphtdocsLaravelblog2resourcesviewsadmindashboard.blade.php)

create_users_table


    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();

        });
    }

create_departments_table

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

Department.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Department extends Model
{

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

public function department()
{
    return $this->belongsTo(Department::class);
}

}

User.php

<?php

namespace App;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

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', "AdminDashboardController@index");
   // Route::get('/dashboard{id}', "AdminDashboardController@index");
    Route::get('/role-register','AdminDashboardController@registered');
    Route::get('/role-edit/{id}', 'AdminDashboardController@registeredit');   
    Route::put('/role-register-update/{id}', 'AdminDashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'AdminDashboardController@registerdelete');
    Route::post('/save-user', 'AdminDashboardController@store');


    Route::get('/department', 'AdminDepartmentController@index');
    Route::post('/save-department', 'AdminDepartmentController@store');
    Route::get('/department-edit/{id}', 'AdminDepartmentController@edit');
    Route::put('/department-update/{id}', 'AdminDepartmentController@update');
    Route::delete('/department-delete/{id}', 'AdminDepartmentController@delete');


});
Auth::routes();

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

I have tried this too but still the same.

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

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

4

Answers


  1. In your web.php,
    replace this:

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

    with this:

    Route::get('/dashboard', 'AdminDashboardController@index' );
    

    In you Dashboard controller, replace this:

    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'));        
    }
    

    with this:

    public function index()
    {
        $users= User::all();
        $departments = Department::with('users')->get();
        return view('admin.dashboard',compact('departments','users'));        
    }
    
    Login or Signup to reply.
  2. Route::get('/dashboard', function () {
        return view('admin.dashboard');
    });
    

    Here’s your problem. You’re returning the dashboard view without passing it the list of departments.

    This route should be using the DashboardController@index ( and your commented code should be uncommented) – which gets the list of departments and returns the view while passing in the list.

    Better yet if you used the URL /departments and a DepartmentsController…

    Login or Signup to reply.
  3. can you try this? see if it changes the error?

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

    comment out this.

    // Route::get('/dashboard', 'AdminDashboardController@index' );
    

    Also in you balde file you need to chenge to this, this will give you all the department.

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

    Update

    <?php
    
    namespace App;
    
    use IlluminateDatabaseEloquentModel;
    
    class Department extends Model
    {
    
        protected $table = 'departments';
        protected $fillable = [
            'name',
        ];
        protected $primaryKey = 'id';
    
    public function users()
    {
        return $this->belongsTo(User::class);
    }
    
    }
    
    Login or Signup to reply.
  4. Try changing the User model to have the following relation:

    public function department()
    {
        return $this->belongsTo(Department::class);
    }
    

    In DashboardController change it to the following:

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

    And update the associated route:

    Route::get('/dashboard', "AdminDashboardController@index");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search