Home > OS >  Laravel (show project title in the selected issue)
Laravel (show project title in the selected issue)

Time:11-05

I want to display the project name of the selected project in the issue.

HomeController (show the projects that is assigned to a user)

public function index()
{
    $companies = auth()->user()->companies;
    $projects  = Project::whereIn('company_id',$companies->pluck('id'))->get();

    return view('home',compact('companies','projects'));
}

ProjectController (shows the issues of the selected project)

public function show($id){
    $project = Project::find($id);
    if(!$project)
        abort(404);

    $issues = $project->issues;
    return view('issues', compact('issues'));
}

issue.blade.php

<div class="container">

        <img src="assets/user.png" class="h-10 m-5 inline-block"><span class="font-bold text-xl">{{ auth()->user()->name }}</span>
        
        <span class="font-bold text-xl">{{ $project->title }}</span>
        <h1 class="ml-5 font-bold text-2xl">Issues</h1>
        <div class="grid grid-cols-3 gap-4 md:grid-cols-3 m-5 ">
            @forelse($issues as $issue)
                <div class="bg-pink-700 h-32 rounded-md p-5 transition duration-500 ease-in-out hover:bg-black transform hover:-translate-y-1 hover:scale-110s">
                    <a href="" class="text-xl font-bold m-5 text-white">{{$issue->title}}</a>
                </div>
            @empty

            @endforelse
    </div>
</div>

Routes

Route::get('/home', [\App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::get('/issues/{id}', [\App\Http\Controllers\ProjectController::class, 'show'])->name('projects.show');

CodePudding user response:

Just a hint, instead of using:

 $project = Project::find($id);
    if(!$project)
        abort(404);

You can use $project = Project::findOrFail($id);

Now to your question:

You could pass the $project model to the view and not only the issues.

public function show($id){
    $project = Project::findOrFail($id);
    return view('issues', compact('project'));
}

Then you can get the related issues via the ->issues relationship in your foreach loop:

<div class="container">
            ......
        <span class="font-bold text-xl">{{ $project->title }}</span>
            ......
        <div class="grid grid-cols-3 gap-4 md:grid-cols-3 m-5 ">
            @forelse($project->issues as $issue)
               .....
            @empty
              .....
            @endforelse
    </div>
</div>

  • Related