我有一个将变量输出到视图的方法。在视图中,我检查变量是否为true,然后显示所需的块,如果为false,则不显示块。但由于某种原因,这对我不起作用。
@if($mainAlbum)
<div class="card">
<a href="{{route('allAlbums', ['id' => $user->id])}}"><h1 class="mt-2 mb-2" style="font-size: 0.9rem; margin-left: 5px; color: black;">Плейлисты<img src="{{asset('img/right.png')}}" width="11"> </h1></a>
@foreach($mainAlbum as $album)
<a href="{{route('album', ['id' => $user->id, 'album' => $album->id])}}"><img src="{{$album->cover}}" class="img-fluid"></a>
@endforeach
</div>
@endif
和方法
public function index($id) {
$user = User::find($id);
$posts = $user->profile()->orderBy('created_at', 'desc')->paginate(2);
$mainVideo = $user->profileVideo()->orderBy('created_at', 'desc')->limit(1)->get();
$mainAlbum = $user->profileAlbums()->orderBy('created_at', 'desc')->limit(1)->get();
return view('profile.profile', compact('user', 'posts', 'mainVideo', 'mainAlbum'));
}
问题是get()
总是返回一个集合,不管里面是否有相册,因此@if($mainAlbum)
总是真实的。
我会做以下事情:
在您的控制器中:
public function index($id) {
// switch 'find' with 'findOrFail' this way it will throw a 404 if no user is found
$user = User::findOrFail($id);
$posts = $user->profile()->orderBy('created_at', 'desc')->paginate(2);
// use 'first' instead of 'get', so it will return a model or null instead of a collection
$mainVideo = $user->profileVideo()->orderBy('created_at', 'desc')->first();
$mainAlbum = $user->profileAlbums()->orderBy('created_at', 'desc')->first();
return view('profile.profile', compact('user', 'posts', 'mainVideo', 'mainAlbum'));
}
- 不要使用
find()
,而是使用findOrFail()
,因此如果找不到用户,页面将抛出404错误 - 由于您使用的是
limit(1)
,因此可以使用first()
而不是get()
,first()
将返回模型或null,get()
将始终返回一个集合—不管它是否包含模型
在您看来:
@if($mainAlbum)
<div class="card">
<a href="{{ route('allAlbums', ['id' => $user->id]) }}">
<h1 class="mt-2 mb-2" style="font-size: 0.9rem; margin-left: 5px; color: black;">
Плейлисты <img src="{{ asset('img/right.png') }}" width="11">
</h1>
</a>
<a href="{{ route('album', ['id' => $user->id, 'album' => $mainAlbum->id]) }}">
<img src="{{ $mainAlbum->cover }}" class="img-fluid">
</a>
</div>
@endif
- 您可以去掉
@foreach
,因为您的变量现在将包含模型而不是集合 - 您的
@if
检查现在有效,因为$mainAlbum
将包含模型或null
在模板中的@if ()
之前,添加{{ dd($mainAlbum) }}
如果您希望显示not块,请检查返回的值是否为falsy(即null
、false
或0
(,而不是truth值,如字符串(即""
、"false"
、"null"
(或Object
或Array
。
如果你期望它显示出来,那么要确保它是一个真实的值。