Provide in view polymorphic relationship data Laravel

Asked

Viewed 284 times

0

I have the models Trainer, Modality and Image using Laravel’s Polymorphic Relations https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-Relations

I want to make this data available in the view and for this I did:

Appserviceprovider.php:

namespace Powerzone\Providers;

use Illuminate\Support\ServiceProvider;
use Powerzone\Image;
use Powerzone\Modality;
use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    $modalities = Modality::all();
    View::share('modalities', $modalities);
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    //
}
}

View:

@extends('site.index')

@section('content')
<section>
    @foreach($modalities as $value)
    <img class="img-responsive" src="{{ asset('/storage/imagem.jpg') }}">
    <h1>{{$value->name}}</h1>
    <p>{{$value->description}}</p>
    @endforeach
</section>
@endsection

Modality.php

namespace Powerzone;

use Illuminate\Database\Eloquent\Model;

class Modality extends Model
{
protected $fillable = [
    'name',
    'description',
];

public function images()
{
    return $this->morphMany('Powerzone\Image', 'imageable');
}

}

Trainer.php

namespace Powerzone;

use Illuminate\Database\Eloquent\Model;

class Trainer extends Model
{
protected $fillable = [
    'name',
    'description',
];

public function images()
{
    return $this->morphMany('Powerzone\Image', 'imageable');
}
}

Image.php

namespace Powerzone;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
protected $fillable = [
    'name',
    'imageable_id',
    'imageable_type',
];

public function imageable()
{
    return $this->morphTo();
}
}

I would like to make available the respective images related to the Modality model only.

  • 1

    Put all three model on the question? Complete!

  • I put the full models.

  • 2

    I think that solves: $modalities = Modality::with('images')->get(); and in the View access $modalities->images

  • It worked. Thank you

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.