Home » Php » php – Departments not showing in Laravel

php – Departments not showing in Laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.


Facade\Ignition\Exceptions\ViewException
Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.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 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);
}

}

User.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', '[email protected]')->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\[email protected]");
   // Route::get('/dashboard{id}', "Admin\[email protected]");
    Route::get('/role-register','Admin\[email protected]');
    Route::get('/role-edit/{id}', 'Admin\[email protected]');   
    Route::put('/role-register-update/{id}', 'Admin\[email protected]');
    Route::delete('/role-delete/{id}', 'Admin\[email protected]');
    Route::post('/save-user', 'Admin\[email protected]');


    Route::get('/department', 'Admin\[email protected]');
    Route::post('/save-department', 'Admin\[email protected]');
    Route::get('/department-edit/{id}', 'Admin\[email protected]');
    Route::put('/department-update/{id}', 'Admin\[email protected]');
    Route::delete('/department-delete/{id}', 'Admin\[email protected]');


});
Auth::routes();

Route::get('/home', '[email protected]')->name('home');

I have tried this too but still the same.

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

@foreach($departments->name as $department)
<td> {{$department}}</td>
@endforeach
How to&Answers:

can you try this? see if it changes the error?


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

comment out this.

// Route::get('/dashboard', 'Admin\[email protected]' );

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

}

Answer:

In your web.php,
replace this:

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

with this:

Route::get('/dashboard', 'Admin\[email protected]' );

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

Answer:

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 [email protected] ( 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…

Answer:

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', "Admin\[email protected]");