foreach inside another foreach

 public function viewAbstract()

// Retrieve all abstracts associated with the authenticated user

$abstracts = Paper::where('user_id', auth()->user()->id)->get(); 

// Preprocess authors

$authors = Author::whereIn('paper_id', $abstracts->pluck('id'))->get()->groupBy('paper_id'); 

// Pass both abstracts and authors to the view 

return view('paper.view_abstracts', compact('abstracts', 'authors')); }

  1. Retrieve Abstracts: We retrieve all abstracts associated with the authenticated user from the papers table using Eloquent ORM. The where('user_id', auth()->user()->id) condition filters the abstracts by the user's ID.

  2. Preprocess Authors: We preprocess the authors associated with the retrieved abstracts. First, we extract the IDs of the abstracts using $abstracts->pluck('id'). Then, we use whereIn('paper_id', ...) to retrieve all authors whose paper_id matches any of the extracted abstract IDs. Finally, we use groupBy('paper_id') to group the authors by their paper_id. This creates a nested structure where each paper_id maps to a collection of authors associated with that paper.

  3. Pass Data to View: We pass both the $abstracts and $authors variables to the view using the compact() function.

In the View:

php
@foreach($abstracts as $abstract)
 <h2>{{ $abstract->title }}</h2>
 <p>{{ $abstract->content }}</p> 
 h3>Authors:</h3>
 @foreach($authors[$abstract->id] ?? [] as $author)
 <p>{{ $author->name }}</p>
 @endforeach 
@endforeach
  1. Iterate Over Abstracts: We iterate over each abstract retrieved in the controller.

  2. Display Abstract Information: We display the title and content of each abstract using {{ $abstract->title }} and {{ $abstract->content }}.

  3. Retrieve Authors for Each Abstract: Inside the loop, we access the authors associated with the current abstract from the $authors variable. We use $authors[$abstract->id] to retrieve the authors whose paper_id matches the ID of the current abstract. We use the ?? [] operator to provide an empty array as a fallback if there are no authors associated with the current abstract.

Comments

Popular posts from this blog

Making Livewire Run on SHared Hosting