phplaravelforeign-keysone-to-many

Laravel how do I access the data in a one to many relationship


I've got a one-to-many relationship between my model Project and Task. I don't know how I can access the data from the tasks table via the data from my project table.

I tried to access the name of the tasks via {{$projects->task->taskname}} and such but it won't let me. I'm basically trying to display all projects with all their tasks in my view.

My tables look like the following

tasks: id | project_id | taskname | description | timeestimated | taskstatus | created_at | updated_at

projects: id | projectname | projectnamenospace | projectdescription | created_at | updated_at

my models:

Task:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = [
        'taskname',
        'description',
        'tasktext',
    ];

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

    public function comment(){
        return $this->hasMany('App\Comment');
    }

    public function project(){
        return $this->belongsTo(Project::class);
    }

}

Project:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    public function task(){
        return $this->hasMany(App::class);
    }
}

My Controller:

<?php

namespace App\Http\Controllers;

use App\Project;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Project $project)
    {
        $ldate = date('Y-m-d H:i:s');

        $projects = Project::all();

        $username = Auth::user()->name;
        return view('dashboard', ['user' => $username, 'ldate' => $ldate, 'projects' => $projects]);
    }
}

Solution

  • assume in your dashboard.blade.php file. You are passing multiple projects and each project has many tasks so you have to run two loops

    @foreach($projects as $key=>$project)
        @foreach($project->task as $taskRow)
            {{$taskRow->taskname}}
        @endforeach
    @endforeach
    

    and change in project model

    public function task(){
        return $this->hasMany(Task::class);
    }