Laravel if condition not working in template? - laravel

I am passing some data in Laravel template. I am using if condition in template but my else part is not working my condition is #if($portfolio->active) class="label label-success" #else class="label label-danger" #endif. I checked {{$portfolio->active}} but it has value 0 so my else part should be run but always if part is running my else part is not working

#if($portfolio->active ==0)
#else
#endif

Write this in your Portfolio model:
protected $casts = ['active' => 'boolean'];
This will make the 'active' field into a boolean. Then you can write your if else as:
#if($portfolio->active)
#else
#endif
This will make your code a little bit more readable. You can avoid the else by doing the converse like:
#if(!portfolio->active)
//your else code here
#endif
//your if code here

You can also use in this way
class="{{ ($portfolio->active) ? 'label label-success' : 'label label-danger' }}

Related

Create anchor tag with route contain under #php script in blade template

Route is not working. How can I write an anchor tag based on some condition? If the condition is true then the anchor tag will be printed with the route. I wrote the code below, but I get an error.
In my blade template:
#php
if (SOMECONDATION) {
echo 'Approve';
}
#endphp
{{ }} is echo-ing. You can use this :
#if($p->name == 0)
Approve
#endif
No need to use echo or anything. Directly use #if #endif and for route use {{ }}
#if($condition)
Approve
#endif

Laravel hide code if requested Path was

Theres any Solution to hide an Code in Laravel for one Page?
With this i can display only one requested page ,Example:
#if (Request::path() == 'message/send')
#endif
Theres an opposite to hide an code for an path?
I have an URL also with after send an Username:
message/send/username
I have try: #if (Request::path() == 'message/send/') and #if (Request::path() == 'message/send/{{$username}}') but dont work.
Thanks
Use request()->is() for this:
#if (request()->is('message/send*'))
you can use segment method in laravel
#php $member = Request::segment(1);#endphp
#if($member =='member')
<style type="text/css"> .test{color: #1a393a !important;</style>
#endif
#endif
Here my first segment is member
The controller is the proper place to handle request specifics. However, if you still wish to do this in your blade view:
#if (Request::path() == 'message/send/' . $username)
You do not use template syntax {{ }} inside expressions. When the blade template is compiled, #if (expr) is converted to <?php if (expr): ?>, so standard PHP applies within the expression.
Route path comparison doesn't work that way. For example:
message/send/jwz104 will never be equal to message/send/{{$username}}
You could compare the route name:
#if(\Request::route()->getName() == 'message.send')
#endif
This also isn't a nice solution. You should handle this in your controller or by view composers.
with core php-
#if (strpos($_SERVER['REQUEST_URI'], "message/send") !== false)
#endif

Check wildcard routes in Laravel 5

In blade, If we want to check that the current route matches with a route or not, we can simply use:
#if(Route::currentRouteName() == 'parameter')
{{ 'yes' }}
#else
{{ 'no' }}
#endif
But what if we want to match it with a wildcard like:
#if(Route::currentRouteName() == 'parameter.*')
{{ 'yes' }}
#else
{{ 'no' }}
#endif
Is there any solution for that?
I have tried "*" and ":any", but it didn't work.
Note: I want to check route, not URL.
Any help would be appreciated.
Thanks,
Parth Vora
Use Laravel's string helper function
str_is('parameter*', Route::currentRouteName())
It'll return true for any string that starts with parameter
I had the same problem. I wanted to toggle an active class based on a URI.
In blade (Laravel 6x), I did:
(request()->is('projects/*')) ? 'active' : ''
You can also make use of Blades Custom If Statements and write something like this in your AppServiceProvider.php:
public function boot()
{
Blade::if('route', function ($route) {
return Str::is($route, Route::currentRouteName());
});
}
then you can use it in a blade view like this:
<li #route('admin.users*') class="active" #endroute>
Users
</li>

How to check if used paginate in laravel

I have a custom view and in some functions, I used paginate and other functions I don't use paginate. now how can I check if I used paginate or not ?
#if($products->links())
{{$products->links()}}
#endif // not work
of course that I know I can use a variable as true false to will check it, But is there any native function to check it ?
This works perfectly. Check if $products is an instance of Illuminate\Pagination\LengthAwarePaginator then display the pagination links.
#if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
#endif
#if($threads->hasPages())
{{ $threads->links() }}
#endif
Simple one!
Try like this
#if($products instanceof \Illuminate\Pagination\AbstractPaginator)
{{$products->links()}}
#endif
You need to check wheater the $products is instance of Illuminate\Pagination\AbstractPaginator. It can be an array or Laravel's Collection as well.
As of laravel 7 you can now do this:
#if( $vehicles->hasPages() )
{{ $vehicles->links() }}
#endif
The beautiful way:
#if ($products->hasMorePages())
{{ $products->links() }}
#endif
Click here to see the official documentation
Don't use a check on the base class of the variable. This could lead to problems with changing base classes in future Laravel versions. Simply check whether the method links exists:
#if(method_exists($products, 'links'))
{{ $products->links() }}
#endif
Corrected code (add "isset"):
#if(isset($products->links()))
{{$products->links()}}
#endif
Shorter version:
{{$products->links() ?? ''}}
It will work for paginate, simplePaginate and when there is no pagination. The solution with "$products->hasMorePages()" will not display pagination links on the last page.
Another way:
#if (class_basename($products) !== 'Collection')
{{ $products->links() }}
#endif
You can use PHP function: get_class($products) - to get full class name.
Laravel should have some function to check ->paginate() is in use.
just write paginate(0) instead of get()
Blade Template: simply use {{$products->links}}. no #if #endif needed.
laravel paginate have 2 type :
simplePaginate() will return \Illuminate\Pagination\Paginator
paginate() will return Illuminate\Pagination\LengthAwarePaginator
Based on the above conditions, you can try this solution :
#if(
$products instanceof \Illuminate\Pagination\Paginator ||
$products instanceof Illuminate\Pagination\LengthAwarePaginator
)
{{ $products->links() }}
#endif
Juse use below format
#if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
#endif
#if($products->currentPage() > 1)
{{$products->links()}}
#endif

How to Get the Current URL Inside #if Statement (Blade) in Laravel 4?

I am using Laravel 4. I would like to access the current URL inside an #if condition in a view using the Laravel's Blade templating engine but I don't know how to do it.
I know that it can be done using something like <?php echo URL::current(); ?> but It's not possible inside an #if blade statement.
Any suggestions?
You can use: Request::url() to obtain the current URL, here is an example:
#if(Request::url() === 'your url here')
// code
#endif
Laravel offers a method to find out, whether the URL matches a pattern or not
if (Request::is('admin/*'))
{
// code
}
Check the related documentation to obtain different request information: http://laravel.com/docs/requests#request-information
You can also use Route::current()->getName() to check your route name.
Example: routes.php
Route::get('test', ['as'=>'testing', function() {
return View::make('test');
}]);
View:
#if(Route::current()->getName() == 'testing')
Hello This is testing
#endif
Maybe you should try this:
<li class="{{ Request::is('admin/dashboard') ? 'active' : '' }}">Dashboard</li>
To get current url in blade view you can use following,
Current Url
So as you can compare using following code,
#if (url()->current() == 'you url')
//stuff you want to perform
#endif
I'd do it this way:
#if (Request::path() == '/view')
// code
#endif
where '/view' is view name in routes.php.
This is helped to me for bootstrap active nav class in Laravel 5.2:
<li class="{{ Request::path() == '/' ? 'active' : '' }}">Home</li>
<li class="{{ Request::path() == 'about' ? 'active' : '' }}">About</li>
A little old but this works in L5:
<li class="{{ Request::is('mycategory/', '*') ? 'active' : ''}}">
This captures both /mycategory and /mycategory/slug
Laravel 5.4
Global functions
#if (request()->is('/'))
<p>Is homepage</p>
#endif
You can use this code to get current URL:
echo url()->current();
echo url()->full();
I get this from Laravel documents.
I personally wouldn't try grabbing it inside of the view. I'm not amazing at Laravel, but I would imagine you'd need to send your route to a controller, and then within the controller, pass the variable (via an array) into your view, using something like $url = Request::url();.
One way of doing it anyway.
EDIT: Actually look at the method above, probably a better way.
You will get the url by using the below code.
For Example your URL like https//www.example.com/testurl?test
echo url()->current();
Result : https//www.example.com/testurl
echo url()->full();
Result: https//www.example.com/testurl?test
For me this works best:
class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"
A simple navbar with bootstrap can be done as:
<li class="{{ Request::is('user/profile')? 'active': '' }}">
Profile
</li>
The simplest way is to use: Request::url();
But here is a complex way:
URL::to('/').'/'.Route::getCurrentRoute()->getPath();
There are two ways to do that:
<li{!!(Request::is('your_url')) ? ' class="active"' : '' !!}>
or
<li #if(Request::is('your_url'))class="active"#endif>
You should try this:
<b class="{{ Request::is('admin/login') ? 'active' : '' }}">Login Account Details</b>
The simplest way is
<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>
This colud capture the contacts/, contacts/create, contacts/edit...
For named routes, I use:
#if(url()->current() == route('routeName')) class="current" #endif
Set this code to applied automatically for each <li> + you need to using HTMLBuilder library in your Laravel project
<script type="text/javascript">
$(document).ready(function(){
$('.list-group a[href="/{{Request::path()}}"]').addClass('active');
});
</script>
instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.
In Blade file
#if (Request::is('companies'))
Companies name
#endif
class="nav-link {{ \Route::current()->getName() == 'panel' ? 'active' : ''}}"
Another way to write if and else in Laravel using path
<p class="#if(Request::is('path/anotherPath/*')) className #else anotherClassName #endif" >
</p>
Hope it helps
Try this:
#if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
<li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
#endif
For Laravel 5.5 +
<a class="{{ Request::segment(1) == 'activities' ? 'is-active' : ''}}" href="#">
<span class="icon">
<i class="fas fa-list-ol"></i>
</span>
Activities
</a>
1. Check if URL = X
Simply - you need to check if URL is exactly like X and then you show something. In Controller:
if (request()->is('companies')) {
// show companies menu or something
}
In Blade file - almost identical:
#if (request()->is('companies'))
Companies menu
#endif
2. Check if URL contains X
A little more complicated example - method Request::is() allows a pattern parameter, like this:
if (request()->is('companies/*')) {
// will match URL /companies/999 or /companies/create
}
3. Check route by its name
As you probably know, every route can be assigned to a name, in routes/web.php file it looks something like this:
Route::get('/companies', function () {
return view('companies');
})->name('comp');
So how can you check if current route is 'comp'? Relatively easy:
if (\Route::current()->getName() == 'comp') {
// We are on a correct route!
}
4. Check by routes names
If you are using routes by names, you can check if request matches routes name.
if (request()->routeIs('companies.*')) {
// will match routes which name starts with companies.
}
Or
request()->route()->named('profile')
Will match route named profile. So these are four ways to check current URL or route.
source
#if(request()->path()=='/path/another_path/*')
#endif
Try This:
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">
<a href="{{ url('/Dashboard') }}">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li>
There are many way to achieve, one from them I use always
Request::url()
Try this way :
registration

Resources