Laravel-medialibrary: how can i get media collection

Created on 18 Aug 2019  路  4Comments  路  Source: spatie/laravel-medialibrary

that is my codes

public function index()
{
$avatars=articles::all()->getMedia();
dd( $avatars);
}
but i get this error
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::getMedia does not exist.

Most helpful comment

instead u can do this:

$articles = Article::with('media')->get();

return view('/*view name*/')->with('articles', $articles);

in your view, loop like so:

@foreach ($articles as $article)
  @foreach ($article->getMedia('sliders') as $image)
  <div class="-item">
      <img src="{{ asset($image->getUrl()) }}">
  </div>
  @endforeach
@endforeach


// if single image in the collection, you can just use $article->getFirstMediaUrl()

All 4 comments

You can't do that i beleive.

Media are associated to a model, not a collection of models.

articles::first()->getMedia() // this will work

thank you, he send back the last recording, I wish to have all the colletion of the table

I found in solution with a brother(Bitfumes, https://bitfumes.com) on skype, here is the solution
$ppp=[];
$at=articles::all();
Foreach($at as $article){
$ppp[]=$article->getMedia('sliders');
}

instead u can do this:

$articles = Article::with('media')->get();

return view('/*view name*/')->with('articles', $articles);

in your view, loop like so:

@foreach ($articles as $article)
  @foreach ($article->getMedia('sliders') as $image)
  <div class="-item">
      <img src="{{ asset($image->getUrl()) }}">
  </div>
  @endforeach
@endforeach


// if single image in the collection, you can just use $article->getFirstMediaUrl()
Was this page helpful?
0 / 5 - 0 ratings

Related issues

aaronfullerton picture aaronfullerton  路  4Comments

drtheuns picture drtheuns  路  3Comments

mokhosh picture mokhosh  路  3Comments

swash13 picture swash13  路  3Comments

Nks picture Nks  路  3Comments