来自 id 的显示名称给我 "Trying to get property 'proj_title' of non-object"

Display name from id gives me "Trying to get property 'proj_title' of non-object"

我有一个表单,我在其中提交了来自 "project";

的 ID
    <div class="form-group">
        <label for="Project">Project</label>
        <select name="proj_id" class="form-control">
            @if (count($project) == 0)          
            <option>There are no projects.</option>
            @else
                @foreach($project as $project)
                    <option value="{{$project->proj_id}}">{{$project->proj_title}}</option>
                @endforeach
            @endif

        </select>
    </div>

这部分工作正常,它将 proj_id 插入到数据库中,但是当我返回索引时,我想显示该 ID 中的项目名称。 这是我的索引;

<tbody class="">
        @foreach ($task as $task)
        <tr>
            <td>{{$task->task_id}}</td>
------->    <td>{{$projects->find($task->proj_id)->proj_title}}</td>
            <td>{{$task->task_title}}</td>
            <td>{{$task->task_desc}}</td>
            <td>{{$task->status}}</td>
            <td>{{$task->priority}}</td>
            <td>{{$task->created_by}}</td>
            <td>{{$task->created_at}}</td>
            @if (Auth::user()->role=='admin')
            <td>

事实上,它给了我标题中的错误。

如果我用 $task->proj_id 更改该行,它会毫无问题地显示。

这也是我在 TaskController 中的索引函数:

    public function index()
    {
        return view('tasks.index', [
            'task' => Task::all(),
            'projects' => Project::all(),
        ]);
    }

这些是我的关系: 项目模型;

class Project extends Model
{
    protected $primaryKey = 'proj_id';
    protected $fillable = ['proj_title','proj_desc','client_id','created_by'];



    public function client (){
        return $this->belongsTo('App\Client');
    }
    public function tasks (){
        return $this->hasMany('App\Task');
    }

}

任务模型;

class Task extends Model
{
    protected $primaryKey = 'task_id';

    protected $fillable = ['task_title','task_desc','status','priority','person_id','proj_title','proj_id','created_by'];

    public function project(){

        return $this->belongsTo('App\Project','proj_id');
    }


}

提前致谢

成功

<td>{{$task->project->proj_title}}</td> 它应该可以正常工作,因为任务和项目具有 belongsTo 关系,您应该能够使用 $task->project 获得与 $task 相关的项目模型。