When i have no images uploaded i get this undefined offset error. I tried to fix this with an if statement in blade, but that did not fix the problem. How can I fix this error without making the image upload mandatory?
@foreach ($mediaItems as $image)
<div class='py-2'>{{ $image }}</div>
@endforeach
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class PostController
{
public function __invoke(Post $post)
{
$mediaItems = $post->getMedia('multi_collection');
$mediaItems[0]->getUrl('medium-size');
return view('posts.show', compact('post', 'mediaItems'));
}
}
@michaloravec Thank you so much man. You answered so much of my questions. I don't know what i would do without your help.
@nakov I already gave michaloravec the best answer, but your solution sounds logic. Can you tell which one you would prefer over the other and why? michaloravec's solution is checking for a first item and yours is checking for items in genaral, right? Whats best practice?
@troj my answer was more on what throws the error for you here, I will remove that line completely as you are not doing anything with the result of that line.
Michael's answer is better in this case, while I still don't know why you would check if it is not empty, when even if it is the @foreach won't throw that error, as the result should be an empty collection and in the blade won't print anything.
@nakov Thank you for your explanation, i think you might be right, I had that line in there because i had a different way of presenting the data first. I placed the variable in the source of an image, so i thought i needed the getUrl to do that. But i guess it's not necessary anymore. I deleted that line and the problem is solved!
So actually you might have given me the best answer in the end, sorry @michaloravec but i need to give @nakov the best answer
@michaloravec you're absolutely right, but i'm doing my best to learn and understand code made by pro's. I'm a more a webdesigner than programmer, so I still have a lot to learn. And I always appreciate the help you guys give.
I'm a bit confused right now whats fair or not, If I need to give you back the best answer because of the way I asked the question, i'll do that, no problem. But for me someone pointing out that that line was unnecessary was actually the solution for my problem.