Home > Net >  How to pass joined variable to view
How to pass joined variable to view

Time:12-22

Laravel seems to have changed several times on syntax and how to do things, so it's difficult to find a modern solution for the problems as a new Laravel developer.

I am trying to display an Album object in the view-album.blade.php file and JOIN another table(/model) which is called AlbumImages. The AlbumImages holds the url (for the image path) and album_id property while the Album itself holds the other data such as title and so on.

This function used to display the Album correctly before I joined the two tables (in AlbumController.php):

public function displayAlbum(Album $album) {
    return view('view-album', ['album' => $album]);
}

Route in web.php:

Route::get('/album/{album}', [AlbumController::class, "displayAlbum"])->middleware('auth');

The problem is that I want to join the two tables in order to access the Album images which are stored in the public image folder and return the correct images to the view (using the url column in the album_images table).

I've tried this (AlbumController.php):

public function displayAlbum(Album $album) {
    $album_combined = DB::table('albums')
        ->join('album_images', 'albums.id', '=', 'album_images.album_id')
        ->select('albums.*', 'album_images.*')->get();

    return view('view-album', ['album' => $album_combined]);
}

And this (Album.php model):

public function getAlbumImages() {
    return $this->hasMany(AlbumImages::class, 'album_id', 'id');
}

These solutions doesn't work and the question is how to do this method correctly and should it be done in the Album model function or inside of the AlbumController.php file?

CodePudding user response:

Here is a complete solution using Laravel Eloquent Models & Relationships, hopefully this will give you a clear idea on what you can do and how to achieve the results you are looking for:

Album Model:

// bigInteger: id (AUTO_INCREMENT)
// string: name
public function album_images(){
    return $this->hasMany(AlbumImage::class);
}

AlbumImage Model:

// bigInteger: id (AUTO_INCREMENT)
// bigInteger: album_id
// string: image
public function album(){
    return $this->belongsTo(Album::class);
}

AlbumController:

public function displayAlbum(Album $album) {
    $album->load('album_images');
    return view('view-album', compact('album'));
}

view-album (VIEW):

<h1>{{$album->name}}</h1>
@foreach($album->album_images as $key=> $album_image)
    <p> {{$key}} - <img src="{{$album_image->image}}"> </p>
@endforeach

You can nest this further as needed.

  • Related