[英]laravel make view without blade for solid message
I want to do a function that returns a view, but if the item you're looking for isn't found, just return a hidden message in the view object.我想做一个返回视图的 function,但是如果找不到您要查找的项目,只需在视图 object 中返回一条隐藏消息。
public function getBannerById(string $banner_id): View
$banner = Banner::find($banner_id);
if (!$banner) {
return view()->append('<!-- Banner not found! -->'); // this not work
}
// more code ....
return view('banner', ['banner' => $banner]);
}
You can use the laravel Session for this, if the items isn't found so return to your view with the session message and then in the view you verify if exists the session and display the message.您可以为此使用 laravel Session,如果找不到这些项目,请使用 session 消息返回您的视图,然后在视图中验证 session 是否存在并显示该消息。
In controller:在 controller:
if (!$banner) {
Session::flash('error', "Banner not found!");
return view('view.name'); //
}
In View在视图中
@if (session('error'))
<div class="alert alert-danger" role="alert">
{{ session('error') }}
</div>
@endif
You can simply return Banner not found
OR attach if-else statements in your blade file as below:您可以简单地返回
Banner not found
或在刀片文件中附加 if-else 语句,如下所示:
Controller code: Controller 代码:
<?php
public function getBannerById(string $banner_id): View
$banner = Banner::find($banner_id);
return view('banner', compact('banner'));
}
View blade file:查看刀片文件:
@if(!$banner)
<p> Banner not found!</p>
@else
// Your view you wish to display
@endif
Update:更新:
You can also use findOrFail
method to automatically send 404 response back to the client if the banner is not found.如果找不到横幅,您还可以使用
findOrFail
方法自动将 404 响应发送回客户端。
$banner = Banner::findOrFail($banner_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.