Home > other >  laravel make view without blade for solid message
laravel make view without blade for solid message

Time:04-26

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]);
}

CodePudding user response:

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  role="alert">
         {{ session('error') }}
     </div>
@endif

CodePudding user response:

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);
  • Related