简体   繁体   中英

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.

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.

In 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:

Controller code:

<?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.

$banner = Banner::findOrFail($banner_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM