TechKat's avatar

Laravel Relationships

Hi,

I have an application I am making which will have albums and upload functions.

On a user's album page, I would like to display the latest image stored in the uploads table that was inserted into an album as the cover.

For example, an Album has an id of 1. The uploads table has a column called album_id, where the default value is NULL. There are 10 records in the uploads table, but only 4 have the number 1 in the album_id column. The latest upload record will be pulled with the Album model via a relationship.

How can I go about this? My guess is it has something to do with Polymorphic Relations?

0 likes
2 replies
IsaacBen's avatar

If I understood correctly you want to get the last image uploaded per album.

Just do something like this, it should work I believe:

$image = DB::table('uploads')->where('album_id', '=', $id)                                 
                             ->orderBy('created_at', 'desc')->first();
1 like
TechKat's avatar

@IssacBen I would much prefer doing this with Relationships so that the code's much cleaner, if it is possible.

Please or to participate in this conversation.