mercredi 3 avril 2019

How to fix undefined variable error in laravel

I'm very new to this so sincere apologies if this is a silly question!

I have two tables in my database - 'users' and 'departments'. I am trying to assign a 'user' to a 'department' as a department manager and storing their user_id in the department table.

What I want to do is be able to choose from a dropdown of users in the create department form, but I keep getting the error below:

Undefined variable: users (View: /home/vagrant/code/PortfolioManager/resources/views/admin/departments/index.blade.php)

Would anyone have any idea where I am going wrong? I have been trying to resolve this for 2 days.

My Department Model code is below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Department extends Model
    {
        protected $fillable = [
            'name',
            'user_id'
        ];

        public function user(){

            return $this->belongsTo('App\User');
        }
    }

My Controller is here also:

<?php

namespace App\Http\Controllers;

use App\Department;
use App\Http\Requests\StoreDepartmentRequest;
use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;

class AdminDepartmentsController extends Controller
{
    public function index()
    {
        $departments = Department::all();

        return view('admin.departments.index', compact('departments'));
    }


    public function create()
    {
        $users = User::lists('name', 'id')->all();
        return view('admin.departments.index', compact('users'));
    }


    public function store(StoreDepartmentRequest $request)
    {
        Department::create($request->all());

        return redirect('admin.departments.index');
    }

My index.blade page is here:

<h1>Departments</h1>

<div class="col-sm-6">

    {!! Form::open(['method'=>'POST', 'action'=>'AdminDepartmentsController@store']) !!}

    
    <div class="form-group">
        {!! Form::label('name', 'Department Name:') !!}
        {!! Form::text('name', null, ['class'=>'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::label('user_id', 'Department Manager:') !!}
        {!! Form::select('user_id', ['' => 'Choose Department Manager'] + $users, null, ['class'=>'form-control']) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Create Business Department', ['class'=>'btn-btn-primary']) !!}
    </div>

    {!! Form::close() !!}


</div>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire