Do you know spacebar? Start using it.
With eager loading you get all your images.
$albums = Album::with('images')->get();
Always return redirect inside store method.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm storing albums in table albums and the images in table images with relations but i cannot find the logic to show the images from the blade Index/Store Method in controller
public function index()
{
$albums=Album::all();
return view('admin.albums.all',compact('albums'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$album=Album::create([
'name'=>$request->name,
'price'=>$request->price,
'image'=>$request->image,
'category_id'=>$request->category_id,
]);
foreach($request->images as $image){
$filename = $image->store('album');
$images=Image::create([
'album_id' => $album->id,
'filename' => $filename
]);
}
$albums=Album::all();
return view('admin.albums.all',compact('albums'));
}
all.blade.php
<tbody>
@foreach ($albums as $album)
<tr>
<th scope="row">{{$album->id}}</th>
<td>{{$album->name}}</td>
<td>{{$album->category_id}}</td>
<td><img style="width:5vw; hieght:5vh" src="{{$album->id}}" alt=""></td>
<td>
<a href="{{route('albums.show',$album->id)}}" class="btn btn-success">Show</a>
@if (Auth::user()->role_id==1)
<a href="{{route('albums.edit',$album->id)}}" class="btn btn-warning">Edit</a>
<form action="{{route('albums.destroy',$album->id)}}" method="post" class="d-inline">
@csrf
@method('DELETE')
<input type="submit" class="btn btn-danger" value="Delete" />
</form>
@else
@endif
</td>
</tr>
@endforeach
</tbody>
Image Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = ['album_id','filename'];
public function images(){
return $this->belongsTo(Album::class,'images_id','id');
}
}
Album Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Album extends Model
{
use HasFactory;
protected $fillable = [
'name',
'category_id',
];
public function categories(){
return $this->belongsTo(Category::class,'category_id','id');
}
public function images(){
return $this->HasMany(Image::class);
}
}
@karimali1337 well $album->images will be a Collection, so you would need a nested loop to iterate over the images, e.g.
@foreach ($albums as $album)
@foreach ($album->images as $image)
< img style="width:5vw; height:5vh" src="{{$image->filename}}" alt="">
@endforeach
@endforeach
Please or to participate in this conversation.