Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

karimali1337's avatar

Showing images from DB

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);
    }
}

0 likes
28 replies
MichalOravec's avatar

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.

Tray2's avatar

You can do a foreach on $album->images, I recommend eagar loding the relation in your controller.

$albums = Album::with('images')->get();

However if you have a shitload of images and albums you need to paginate the albums and the pictures.

karimali1337's avatar

@Tray2 the album related to images table with the ID i've tried

$albums = Album::with('images')->get();

but its not working.

tykus's avatar

@karimali1337 its not working? Maybe you need to be more descriptive!

Also, what is the story with the relationships; Image has a BelongsTo relationship named images; and you have a non-conventional foreign key, but Album has a HasMany images relationship without a non-conventional key?

karimali1337's avatar

@tykus i mean that i used the spacebar but i don't know how to show them in blade as the relation between albums and images related with the album ID,

about the relations im practicing on it in this small project because i don't understand them well then i'm trying to practicing.

karimali1337's avatar

@Tray2

^ Illuminate\Database\Eloquent\Collection {#1224 ▼
  #items: array:4 [▼
    0 => App\Models\Album {#1234 ▼
      #connection: "mysql"
      #table: "albums"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:5 [▶]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: array:2 [▶]
      #guarded: array:1 [▶]
    }
    1 => App\Models\Album {#1235 ▶}
    2 => App\Models\Album {#1236 ▶}
    3 => App\Models\Album {#1237 ▶}
  ]
  #escapeWhenCastingToString: false
}
tykus's avatar

@karimali1337 okay 🤷‍♂️

Still what is up with the relationship? What is the foreign key on the images table?

karimali1337's avatar

@tykus when i upload album the images saved in table images with the id of album in table albums

tykus's avatar

@karimali1337 what is the name of the column on the images table which relates to the ID on albums?

tykus's avatar

@karimali1337 so why is this not working - what are you getting???

$albums = Album::with('images')->get();
karimali1337's avatar

@tykus i don't know what to write in my all.blade.php to preview the image here's my blade all info like id ,album , category is shown right but the images is not previewed

Index in album controller

    public function index()
    {
        $albums = Album::with('images')->get();
                return view('admin.albums.all',compact('albums'));
    }

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>
tykus's avatar
tykus
Best Answer
Level 104

@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
karimali1337's avatar

@tykus When i apply this code the output looks like i've deleted the

    <td><img style="width:5vw; hieght:5vh" src="{{$image->filename}}" alt=""></td>

and the image not previewed

Tray2's avatar

@karimali1337 Is the path to the image correct and line up with where the image actually is in your filesystem?

karimali1337's avatar

@Tray2 i was storing in folder name albums, and the images was stored in right way, now if im inserted new album it doesn't store photo but store a temp file named php008.tmp

Please or to participate in this conversation.