To display only the notes that belong to a specific notepad, you need to adjust your query logic and the way you pass data to your Blade view. Instead of fetching all notes separately, you should leverage the Eloquent relationships you've defined to fetch notes related to each notepad.
Here's how you can modify your Livewire component and Blade view to achieve this:
Livewire Component
In your Notepads Livewire component, you should fetch the notepads with their related notes using Eloquent's with method. This will eager load the notes for each notepad, reducing the number of queries and making it easier to access related data.
namespace App\Livewire;
use Livewire\Component;
use App\Models\Notepad;
use Illuminate\Support\Facades\Auth;
class Notepads extends Component
{
public function render()
{
return view('livewire.notepads', [
'notepads' => Notepad::with('note')->get()
]);
}
}
Blade View
In your Blade view, you can now iterate over each notepad and its related notes directly. This ensures that only the notes belonging to each specific notepad are displayed.
<div class="grid auto-rows-min gap-4 md:grid-cols-3">
@foreach($notepads as $notepad)
<div class="relative aspect-video overflow-hidden rounded-xl border border-neutral-200 dark:border-neutral-700" wire:key="{{ $notepad->id }}">
<div class="w-full bg-gray-800 py-2">
<h1 class="m-1 px-4 font-extralight">
{{ $notepad->table_name }}
</h1>
</div>
<div class="font-extralight text-sm">
@foreach($notepad->note as $note)
<p class="mt-2 px-4">
{{ $note->note_item }}
</p>
@endforeach
</div>
</div>
@endforeach
</div>
Explanation
-
Eager Loading: By using
Notepad::with('note')->get(), you are eager loading the notes for each notepad. This means that when you retrieve the notepads, their associated notes are also retrieved in a single query, which is more efficient. -
Blade Iteration: In the Blade view, you iterate over
$notepadsand for each notepad, you access its related notes using$notepad->note. This ensures that only the notes associated with the current notepad are displayed.
This approach is clean and leverages Laravel's Eloquent ORM to handle relationships efficiently.