Laravel5 route, Different in the blade template depending on routing - laravel-5

I'm trying to achieve something like the following:
Depending on the routing that follows the address, it will display differently on the screen.
if /register ->
http://laravel.dev/register
resources/views/layouts/master.blade.php
<nav class='navbar navbar-toggleable-md bg-info fixed-top navbar-info' color-on-scroll='500'>
else if /home ->
http://laravel.dev/home
resources/views/layouts/master.blade.php
<nav class='navbar navbar-toggleable-md bg-info fixed-top navbar-transparent' color-on-scroll='500'>
Thanks in advance.

Try this:
#if(request()->is('register'))
<nav class='navbar navbar-toggleable-md bg-info fixed-top navbar-info' color-on-scroll='500'>
#elseif(request()->is('home'))
<nav class='navbar navbar-toggleable-md bg-info fixed-top navbar-transparent' color-on-scroll='500'>
#endif

One idea is using a route parameter of some kind as a flag to tell your page which "context" it's loading in.
For example, depending on how your routes are setup, you could add code either in the route function or controller function like:
$url = parse_url($_SERVER['REQUEST_URI']);
$path = $url['path'];
$isRegisterPage = in_array("register", explode("/", $path));
Then you can check in your blade template for the variable "$isRegisterPage" to determine which NavBar to load.

Related

How to handle the if statement in a view called from multiple places when passing a variable to compact

I have the following function in the controller:
public function tasks(Client $client)
{
$tasks = $client->tasks;
$client_name = $client->name;
return view('task.index', compact('tasks','client_name'));
}
and as task_index is called from multiple places, I am handling h1 as shown below:
<div class="col-12 col-md-10 d-flex justify-content-center">
#if($client_name)
<h1>List of overall customer tasks {{$client_name}}</h1>
#else
<h1>List of tasks</h1>
#endif
</div>
only when I click on the button to show all the tasks I get the error
Undefined variable $client_name
so the if is not working.
Can anyone tell me how to do please?
Use the Blade #isset directive rather than #if:
#isset($client_name)
<h1>List of overall customer tasks {{$client_name}}</h1>
#else
<h1>List of tasks</h1>
#endisset
If You are using $client_name in different blade, Try to share your variable using View::share() in the AppServiceProvider it will act as component and you can use it across all the blade template
from AppServiceProvider class
$tasks = $client->tasks;
$client_name = $client->name;
ex: View::share(['client_name'=>$client_name] i already use it in my project
If you are using multiple blade files within each other, you must pass the variable you want to re-use in each subsequent blade file
eg.
<h1>List of overall customer tasks {{$client_name}}</h1>
#include('another.blade.php', ['client_name' => $client_name])

Laravel pagination with URL parameter

I have a Laravel application. One of the pages can be reached via the following URL
http://localhost:8000/items/gallery?item_type=glasses
As the amount of items to be shown can be quite substantial, I'm using pagination. I have the following code in my view:
#foreach($media as $media_item)
<div class="col-md-3">
<div class="card">
<img class="card-img-top" src="{{ asset('storage/'.$media_item->id .'/'. $media_item->file_name) }}" ">
</div>
</div>
#endforeach
{{ $media->links() }}
and in the controller, I'm using:
$media = Media::paginate(5);
The pagination buttons are shown and work for the 1st one. Then when I click on the second (or third or fourth...) one, I get the following error message:
Method Illuminate\Database\Eloquent\Collection::links does not exist.
I see the link is trying to reach:
http://localhost:8000/beeritems/gallery?page=2
whereas I need:
http://localhost:8000/beeritems/gallery?item_type=glasses&page=2
In Laravel, how can I change the links() method to include the part after the question mark?
You must use ->appends() methods
$media = Media::paginate(5);
$media->appends($request->all());
you can use laravel basic URLs instead of getting gallery images with URL get parameters.
something like this:
define Route like this
/items/gallery/{types}
then using it like
http://localhost:8000/items/gallery/glasses
in this case you don't get that error anymore

How to put route in anchor tag in laravel 5.2

I've gone through many of the articles below, which explains generating link from named route, but unable to solve my problem.
Tutorial 1
Tutorial 2
Tutorial 3
Following is the defined routes:
Route::get('/nitsadmin/dashboard', function () {
return view('nitsadmin.dashboard');
});
And I'm calling link in anchor tag:
<a id="index" class="navbar-brand" href="{{Html::linkRoute('/nitsadmin/dashboard')}}">
<img src="../img/admin/nitseditorlogo.png" alt="Logo">
</a>
I'm getting following error:
For coders using routes names, simply they can use to() method:
return redirect()->to(route('dashboard').'#something');
In templates:
{{ route('dashboard').'#something' }}
You can do this quite simply with the url() helper.
Just replace your anchor tag like so:
<a id="index" class="navbar-brand" href="{{url('/nitsadmin/dashboard')}}">
<img src="../img/admin/nitseditorlogo.png" alt="Logo">
</a>
Regarding the image that you have used in there, if these were to be stored in your public folder then you could always use the asset() helper. This would help you turn your absolute links to in dynamic ones.
Lets say you have route like these....
Route::get('/nitsadmin/dashboard', function () {
return view('nitsadmin.dashboard');
});
Route::get('/land', 'HomeController#landingPage');
Route::get('/role-permission/add', ['as' => 'mp.rp.add', 'uses' => 'RolePermissionMapController#add']);
so you can link like this --
Click
Click
Click
Click
In your route put name and
Route::get('/nitsadmin/dashboard', function () {
return view('nitsadmin.dashboard')->name(nitsadmin.dashboard);
});
Go to your html where you link the url
<a id="index" class="navbar-brand" href="{{route('nitsadmin.dashboard')}}">
<img src="../img/admin/nitseditorlogo.png" alt="Logo">
</a>
Below code will work.
click
In URL it will be like this below line.
127.0.0.1:8000/cardetails/121/cars

Bootstrap Navbar Highlighting in Thymeleaf's layout

I am evaluating spring boot + MVC + bootstrap . One problem I am facing is bootstrap's navbar highlighting problem in thymeleaf.
I hope thymeleaf can judge the tab which should be highlighted.
I searched and found this solution : Bootstrap Navbar Highlighting in Thymeleaf
In the containing(outer) page , it uses
<div th:replace="header::header('home')">
to be replaced header
</div>
to designate the home tab should be highlighted.
And in the contained (inner) page , it uses
<nav class="..." th:fragment="header(activeTab)">
<ul class="nav navbar-nav">
<li th:class="${activeTab == 'home'} ? 'active' : null ">Home</li>
</ul>
to judge this tab should be highlighted or not.
It works for every single page well , but not for layout.
In a layout page , the containing (outer) page is a decorator , which decorates other pages (home / about / contact ...) . The tab value is pending here .
for example
<div th:replace="header::header('home')">
to be replaced header
</div>
<div layout:fragment="content">
layout
</div>
<div th:replace="footer::footer">
to be replaced footer
</div>
I cannot pre-assign home tab in the layout file.
Is there any way to solve it ?
Can it judge by controller or even controller's method ?
environment :
springboot.version 1.3.0.M5
spring.version :4.2.1.RELEASE
Thanks a lot !
It is not a exact solution for your question but maybe you will like the idea. You may use request context path to recognize which tab is actually selected, so you can use ${#httpServletRequest.getContextPath()} and maybe then something like that:
<ul class="nav navbar-nav" th:with="view=${#httpServletRequest.getServletPath()}">
<li th:classappend="${#strings.startsWith(view,'/home')? 'active' : ''}">Home</li>
</ul>
Or you can use ControllerAdvice:
#ControllerAdvice(assignableTypes = { MyController.class })
public class MyControllerAdvice {
#ModelAttribute
public void addAttributes(#RequestParam Map<String, String> params, Model model, HttpServletRequest request) {
String activeTab = ... whatever
model.addAttribute("active_tab", activeTab);
}
}
There is one big disadvantage of using #ControllerAdvice. If you are planning to use Spring WebFlow to create multi-page forms (wizards) then it will not work because WebFlow does not use model attributes.
change this line <nav class="..." th:fragment="header(activeTab)">
to this
<nav class="..." th:fragment="header(activeTab='activeTab')">
it worked for me

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