Display a section according Condition in laravel - php

I have two return varibles from controller to view in Laravel.
return view ('home', compact('books','count'));
Now I want to display one section('content') #if the conditon is true
in my home.blade.php. How I can do this. Now section('content') will display #if condition is false
#if (!empty($books))
#section('content')
#endif

You can use #else, #elseif, #unless
Here is an example
#if (count($books))
section('content')
#else
#section('your other section')
#endif
Hope this helps

Related

how to check is there a value in the other column of table?

In a laravel blade in third line of this code I want to check if parent_id exists in id column or not
please help me!
I'm using laravel 9
#if ($category->parent_id == 0)
no parent
#if ($category->parent_id)
no parent
#else
{{ $category->parent->name }}
#endif
I corrected it this way:
#elseif (empty($category->parent))
Using exists() function for parent()
Not that exists function works just with single relations (belongsTo, hasOne)
// This will run SQL query // returns boolean
$category->parent()->exists(); // Don't forget parentheses for parent()
If you want to save performance and not calling sql query
count($category->parent); // returns 0 if not exist
Balde:
you can use the empty() to check if empty.
#if ($category->parent == 0)
no parent
#elseif (empty($category->parent))
<p>no parent</p>
#else
{{ $category->parent->name }}
#endif
or ?? operator
{{ $category->parent_id ?? 'no parent' }}
You can use the is empty in twig as below:
{% if category is empty %}
<p> No parent </p>
{% endif %}
You can try by using isset() function
#if ($category->parent_id == 0)
no parent
#if (!isset($category->parent_id))
no parent
#else
{{ $category->parent->name }}
#endif

Blade #if / #else returns both statements

I have an #if/#else condition in a Blade file to present different values of a PHP table. The data comes from a Laravel/Livewire controller, and the Blade code that creates the issue is below.
#if(!$course->user_limit)
#if(in_array($course->id, $arrs))
<x-jet-button wire:click="confirmCourseInterest( {{ $course->id}})"
class="bg-orange-500 hover:bg-orange-700">
{{__('Κάντε κλικ για απόσυρση ενδιαφέροντος')}}
</x-jet-button>
#else
<x-jet-button wire:click="confirmCourseInterest( {{ $course->id}})"
class="bg-orange-500 hover:bg-orange-700">
{{__('Κάντε κλικ για εκδήλωση ενδιαφέροντος')}}
</x-jet-button>
#endif
#else
<div class="flex" id="user_limit_reached">
{{ __('User Limit Reached') }}
</div>
#endif
The issue occurs on the outer if/else that irregularly returns both if and else statements. The user_limit is false on the field that has the problem. Why does this happen?
Change your #else to #elseif and pass another logic there.

How to check if a variable has data in laravel blade

I wanted to check if variable is there or not in blade ..for that i have used following lines:
#if(is_null($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
The problem is when there is $products on blade I could show inside of foreach loop but when i get empty variable.I couldn't show the message No Data Found instead it shows only empty space?
is there any problem of checking variable inside of blade?
Controller code :
public function productSearch(Request $request)
{
$name = $request->name;
$products = Product::where('name' , 'like', '%'.$name.'%')->get();
return view('cart.product',compact('products'));
}
I generally use PHP count() :
#if(count($products) < 1)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
You may also check with PHP empty() like :
#if(!empty($products))
As you can see in the documentation :
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse
This code will allow you to parse all the users and display a list of them. if the $users variables is empty, then it will display a paragraph
so for you :
#forelse ($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
As of Laravel 5.7, You can also do this:
#empty(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endempty
You can check like
#if(isset($products) && !empty($products))
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
//
#endforeach
#endif
What about checking length?
#if(count($products)) >= 1)
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Because empty set (i mean a data stucture with zero elements) is not null at all.
php > $a = [];
php > echo is_null($a) ? 1 : 0;
// => 0
is_null Finds whether the given variable is NULL or not. but in our case we need to check whether the value in empty or not for this you can use either isset() or empty() function both work same in your case
while isset — Determine if a variable is set and is not NULL and
empty — Determine whether a variable is empty and also tell variable is set
#if(isset($products) && !empty($products))
#foreach($products as $product)
//
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
Do this,
Check is there any records "->count() > 0" then do foreach,
else alert.
#if ($products->count() > 0 )
#foreach($products as $product)
//enter code here
#endforeach
#else
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endif
For me I will use logic like this
if(!$products->isEmpty()){
return view('cart.product', compact('products'));
}else{
return view('pageerror', compact('products'));
}
then you can call pageerror from your view folder to display any page that does not has data
#forelse($products as $product)
<p>do some thing</p>
#empty
<p>No Products</p>
#endforelse
Refer
Try this
#forelse($products as $product)
//
#empty
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#endforelse
I found the most effective (and by far the easiest way) of accomplishing what you're trying here to be as follows.
Assumption #1: You Know The Variable Exists Within The View.
REMEMBER: an empty array will always return false.
Therefore, there is no real need to run it through a function like empty or is null.
Comparing it to null will tell you if it exists or not.
(You could by-pass this assumption by checking to see if the variable is not equal to NULL (it's kind of bloaty if you've passed that variable through to the view, so in my opinion, I would KEEP IT SIMPLE STUPID [KISS] - if you want, you can go all fancy later when it comes to further refactoring).
ANYWAY..
I would stick to pretty similar code as you have now, maybe something like this here would be the code for your view:
#if(!$products)
<div class="alert alert-warning">
<strong>Sorry!</strong> No Product Found.
</div>
#else
#foreach($products as $product)
// {{ $product . “code goes here.” }}
#endforeach
#endif
and the code for your controller would look something like this (you almost had it, remember: "perfect practice makes perfect!" - but yeah, the controller code:
public function productSearch(Request $request)
{
// Easily obtain the name submitted by the form (I assume via the request object
// dependency injection magic
$name = $request->name;
// I would consider using the DB builder tool, as follows, as there is more docs on it
// see: https://laravel.com/docs/5.6/queries - this will return a collection (iterable)
$products = DB::table(‘products’)
->where('name' , 'like', '%'.$name.’%’)
->get();
// simply passing to the view
return view('cart.product', compact('products'));
}
You would also need to include the Product model, DB (Laravel) and (as per usual) the request object, as follows:
// Laravel Dependencies
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// User Created Model
use App\Product;
Hopefully, this has been helpful!

Laravel - Request::is() doesn't work as it should

I have 4 different titles
users
agencies
end customers
inactive
and i have only one view (one laravel.blade.php file) with this code
#section('title')
#if (Request::is('/admin/users'))
Alle Benutzer
#elseif(Request::is('/admin/agencies'))
Agenturen
#elseif(Request::is('/admin/endcustomers'))
Endkunden
#else
Inactive
#endif
#endsection
and in my layout i have
<title>#yield('title')</title>
and in my routes i have
Route::get('/admin/users', 'AdminController#showUsers');
Route::get('/admin/agencies', 'AdminController#showAgencies');
Route::get('/admin/endcustomers', 'AdminController#showEndCustomers');
Route::get('/admin/inactive', 'AdminController#showInactiveUsers');
And which ever site i call the title is always Inactive
What am i doing wrong....why the title doesn't change?
Well, you can't use the "Request" in the view.
I suggest you send the title from the controller like this:
return view('%the name of the view%', ['title'=>"%Your title%"]);
Then in the view, you can put this
<title> {{$title }} </title>
you've got to echo the title in the #section.
#section('title')
#if (Request::is('/admin/users'))
echo("Alle Benutzer");
#elseif(Request::is('/admin/agencies'))
echo("Agenturen");
#elseif(Request::is('/admin/endcustomers'))
echo("Endkunden");
#else
echo("Inactive");
#endif
#endsection
You can do like this in Blade (view):
#switch(\Route::current()->getName())
#case('/admin/users')
Alle Benutzer
#break
#case('/admin/agencies')
Agenturen
#break
#case('/admin/endcustomers')
Endkunden
#break
#default
Inactive
#endswitch

Laravel 5.2 redirect back with success message

I'm trying to get a success message back to my home page on laravel.
return redirect()->back()->withSuccess('IT WORKS!');
For some reason the variable $success doesn't get any value after running this code.
The code I'm using to display the succes message:
#if (!empty($success))
<h1>{{$success}}</h1>
#endif
I have added the home and newsletter page to the web middleware group in routes.php like this:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
return view('home');
});
Route::post('/newsletter/subscribe','NewsletterController#subscribe');
});
Does anyone have any idea why this doesn't seem to work?
You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.
If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:
return redirect()->back()->with('message', 'IT WORKS!');
Displaying message if it exists:
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
#if(session('success'))
<h1>{{session('success')}}</h1>
#endif
Controller:
return redirect()->route('subscriptions.index')->withSuccess(['Success Message here!']);
Blade
#if (session()->has('success'))
<div class="alert alert-success">
#if(is_array(session('success')))
<ul>
#foreach (session('success') as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
#else
{{ session('success') }}
#endif
</div>
#endif
You can always save this part as separate blade file and include it easily.
fore example:
<div class="row">
<div class="col-md-6">
#include('admin.system.success')
<div class="box box-widget">
You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.
You can replace your code to below code.
return back()->with('message', 'WORKS!');
In the view file replace below code.
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
For more detail, you can read here
back() is just a helper function. It's doing the same thing as redirect()->back()
One way to do that is sending the message in the session like this:
Controller:
return redirect()->back()->with('success', 'IT WORKS!');
View:
#if (session()->has('success'))
<h1>{{ session('success') }}</h1>
#endif
And other way to do that is just creating the session and put the text in the view directly:
Controller:
return redirect()->back()->with('success', true);
View:
#if (session()->has('success'))
<h1>IT WORKS!</h1>
#endif
You can check the full documentation here: Redirecting With Flashed Session Data
I hope it is very helpful, regards.
All of the above are correct, but try this straight one-liner:
{{session()->has('message') ? session()->get('message') : ''}}
In Controller
return redirect()->route('company')->with('update', 'Content has been updated successfully!');
In view
#if (session('update'))
<div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
×
<strong> {{ session('update') }} </strong>
</div>
#endif
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Adi
in Controller:
`return redirect()->route('car.index')->withSuccess('Bein ajoute')`;
In view
#if(Session::get('success'))
<div class="alert alert-success">
{{session::get('success')}}
</div>
#endif

Categories