samedi 6 avril 2019

Displaying data from two tables in Laravel

I'm learning Laravel and have an issue I really can't resolve despite hours of googling. I have three tables - projects, users and project managers. I am trying to create a drop down list in the projects edit.blade that will display the name of the project manager by joining up the user_id from the project manager table to the id of the users table, however I obviously want the PM_ID to be saved when the user chooses a name. I tried creating a join in the edit method of my controller but I am not having any luck. I have set up all my relationships in the model also, I think that they are correct? Can someone tell me where I am going wrong?

My table set up is as follows (I left irrelevant fields out):

    Projects:
       ID, 
       Name, 
       PM_ID

    Users:
       ID, 
       Name

   Project Managers:
      ID, 
      User_ID

Project Controller:

    $project_managers = DB::table('project_managers')
       ->join('users', 'users.id', '=', 'project_managers.user_id')
       ->select('users.name', 'project_managers.id')
       ->lists('users.name', 'project.managers.id')
       ->get();

   return view('admin.projects.edit', compact('project', 'project_managers'));

edit.blade:

    <div class="form-group">{!! Form::label('PM_id', 'Project Manager:') !!}{!! Form::select('PM_id', ['' => 'Choose a PM'], $project_managers, null, ['class'=>'form-control']) !!}</div>

My relationships are:

Project:

    public function project_manager(){
       return $this->belongsTo('App\ProjectManager');
    }

ProjectManager:

    public function user(){
       return $this->belongsTo('App\User');
     }

User:

    public function project_manager(){
      return $this->belongsTo('App\ProjectManager');
     }

With this code I am getting the following error:

      FatalThrowableError in AdminProjectsController.php line 97: Call to a member function get() on array

Any direction on this would be greatly appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire