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);
Related
Why I am getting this error?
ErrorException
Undefined variable: features (View: C:\xampp\htdocs....views\layouts\index.blade.php)
FeaturedController.php
public function index()
{
$features = Feature::get();
return view ('layouts.index')->with(compact('features'));
}
ProductsController.php
public function index()
{
$products = Product::get();
return view ('products')->with(compact('products'));
}
layouts page- index.blade.php
#yield('content')
#foreach($features as $f)
<li>
<div class="prodcut-price mt-auto">
<div class="font-size-15">LKR {{ $f ['features_id'] }}.00</div>
</div>
</li>
#endforeach
view page - index.blade.php
#extends('layouts.index')
#section('content')
#foreach($products as $p)
<div class="mb-2">{{ $p ['prod_sub_category'] }}</div>
<h5 class="mb-1 product-item__title">{{ $p ['prod_name'] }}</h5>
<div class="mb-2">
<img class="img-fluid" src="{{asset('/storage/admin/'.$p ['prod_image_path'] ) }}" alt="Image Description">
</div>
<div class="flex-center-between mb-1">
<div class="prodcut-price">
<div class="atext">LKR {{ $p ['prod_price'] }}.00</div>
</div>
<div class="d-none d-xl-block prodcut-add-cart">
<i class="ec ec-shopping-bag"></i>
</div>
web.php
Route::resource('/products', 'ProductsController');
Route::resource('/layouts/index', 'FeaturedController#index');
Aside from not passing your variables to your blade views appropriately which other answers have pointed out, your trying to access features from a controller that does not have features set.
The controller below sets features and then makes use of it in the layouts.index blade file.
FeaturedController.php
public function index()
{
$features = Feature::get();
return view ('layouts.index')->with(['features' => $features]);
// or
// return view ('layouts.index', compact('features'));
}
While this controller sets products but then makes use of a blade file that extends another blade file that has a features variable in it. This is why your getting the error
ProductsController.php
public function index()
{
$products = Product::get();
return view ('products', compact('products'));
}
And to fix it you must pass the features variable along side products like so:
ProductsController.php
public function index()
{
$products = Product::get();
$features = Feature::get();
return view ('products')->with(['features' => $features, 'products' => $products]);
}
But if more than one blade file is going to extend this layouts.index file then this approach is not advisable, and situations like this is why Taylor Otwell introduced Blade Components. You can now move the features blade view and logic to a component that can wrap around any other file you want or be included.
The documentation is straight forward but if you want me to show you how to implement it to solve your dilemma then hit me up on the comment below.
as u r using data in layout u should use laravel view composer to share data to layout file ref link https://laravel.com/docs/7.x/views#view-composers
in your AppServiceProvider.php
inside boot() add this line
public function boot()
{
\View::composer('layouts.index', function ($view) { // here layout path u need to add
$features = Feature::get();
$view->with([
'features'=>$features,
]);
});
}
It share data based on specif view file like here layouts.index data is send to this view so if u not send data from controller it will get data from view composer
You can change your controller to this:
public function index()
{
$features = Feature::all();
return view ('layouts.index', compact('features'));
}
A your blade you should actually do #section instead:
#section('content')
#foreach($features as $f)
<li>
<div class="prodcut-price mt-auto">
<div class="font-size-15">LKR {{ $f->features_id }}.00</div>
</div>
</li>
#endforeach
#endsection
need print column data in my laravel app. My controller is TaskController.php
public function index()
{
$tasks = Task::all();
return view('tasks.index')->with('tasks', $tasks);
}
index.blade.php file is
#if(isset($tasks))
#foreach ($tasks as $task)
<h1>{{ $task->task_name }}</h1>
#endforeach
#endif
I am going include this index view file in show.blade.php file as following
#include('tasks.index')
but unable to print table data no any errors occurred. how can I print task_name in show view file?
If you are including the index blade inside the show blade, then you need to change your controller and pass data to the final blade (show instead of index) like this
return view('tasks.show')->with('tasks', $tasks);
If you want to show data on task.index then use this code.
public function index()
{
$tasks = Task::all();
//this line will pass $task data to this view
return view('tasks.index',compact('tasks'));
}
When the user save the object in the blade view, a function into my controller execute with post request. If the save was success I want to reload the page with the changes.
So I need to call index() again to get the refreshed data. Also, I want to show a success message. So the steps are:
index() function execute so the user can show his items.
the user choose an item and save it
save(Request $request) is called
everything save fine
save function call index() with sending a parameter with the flash success message?
I have this structure in my controller:
public function index(){
...
return view('agenda')->with(['agenda'=>$response]);
}
public function save(Request $request){
...
// here where I need to return index function with success message
}
How can I solve my problem?
Assuming the save action was called from the index page, simply redirect back
public function save(Request $request){
...
return redirect()->back()->with('message', 'Item saved');
}
If it was called from a different page, redirect to index page. Assuming your index() function matches a route /:
return redirect()->to('/')->with('message', 'Item saved');
Then display the flash message in your index view.
#if(Session::get('message'))
{{ Session::get('message') }}
#endif
For styling, if you are using bootstrap you can do
#if(Session::get('message'))
<div class="alert alert-success">
{{ Session::get('message') }}
</div>
#endif
I have a function where:
After I click the link named "hapus", the related data will be deleted and I want to have a popup alert to show that the data has been deleted.
*sorry for my bad english
*hapus technically means destroy
this the code:
public function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back();
}
Use with() in your controller
function hapus(Request $request, $id)
{
DB::table('kelompok')
->where('id', $id)
->delete();
return redirect()->back()->with('alert', 'Deleted!');
}
In your blade template, retrieve the session after being redirected from controller:
#if (session('alert'))
<div class="alert alert-success">
{{ session('alert') }}
</div>
#endif
Extending #pbwned's answer,
you can also use javascript alert box in your blade view to display the flash session/message.
For example:
<script>
var msg = '{{Session::get('alert')}}';
var exist = '{{Session::has('alert')}}';
if(exist){
alert(msg);
}
</script>
Hope it helps =)
The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
$rules = array(...);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::route('registration')->withErrors($validator);
}
else {
//Some code here...
return Redirect::route('registration')->withMessage('Test message!');
}
}
Template:
#extends('default.base')
#section('main')
#if(!empty($errors->all()))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}
#endforeach
</ul>
</div>
#endif
#if(isset($message))
{{ $message }}
#endif
#stop
That is because errors is a special case. When creating a view, Laravel check's if there is a session variable with the name errors. If so it will then pass the contents as $errors to the view.
Illuminate\View\ViewServiceProvider#registerSessionBinder
if ($me->sessionHasErrors($app))
{
$errors = $app['session.store']->get('errors');
$app['view']->share('errors', $errors);
}
This means you either use Session::has('message') and Session::get('message') in your view or you add a View Composer that does basically the same that Laravel does with errors:
View::composer('*', function($view){
if(Session::has('message')){
$view->with('message', Session::get('message'));
}
});