Add "active" class in blade depending on current translated Laravel route - php

Using the package mcamara/laravel-localization in Laravel 5.1 I managed to localize my site and also to translate the routes. The problem is now the following: How can I add a custom class "active" via blade template depending on the current route?
I have tried so far using HTML::macro but it seems the package laravelcollective/html: "5.1.*" isn't fully compatible (especially macros) with L5.1.
Even if I would manage to use an macro I can not use the Request::is('about') because the routes are translated. I'm pretty sure here has to be an easy approach...
Example routes:
www.sitename.com/en/about = www.sitename.com/ro/despre => route to same controller/action

Try this!
<li class="#if (Request::is('/')) {{'active'}} #endif">Home <span class="sr-only">(current)</span></li>
<li class="#if (Request::is('about')) {{'active'}} #endif">About</li>
<li class="#if (Request::is('contact')) {{'active'}} #endif">Contact</li>

With inspiring help from #keithm and from here I did the following:
First extend blade with a new directive, built directly in the AppServiceProvider.php
Blade::directive('activeState', function($expression) {
return '<?php echo activeClass('. $expression . '); ?>';
});
Then in your helpers file (if you don't have one you can create it into app/Http/helpers.php) add the following
function activeClass($url) {
return Request::url() == $url ? 'active' : '';
}
In blade directly use then the following directive:
<a href="{{ URL::route('front.portfolio.index') }}" class="nav-block #activeState(URL::route('front.portfolio.index'))">

Not sure if I got your question but is this what you're looking for?
<span class="someClass #if (Request::url('/myurl') active #endif"></span>
Sorry missed that part of the question :).
I didn't test it this way but it should work:
#if (Request::url($variable or $pattern .'/restofuri')

A little late to the party, but i also had the same issue and solved it with the laravel helper function url()->current() and the localization package helper function localizeURL
<a href="{{LaravelLocalization::localizeURL(trans('routes.my-route'))}}"
class="{{(url()->current() == LaravelLocalization::localizeURL(trans('routes.my-route'))) ? "active" : "" }}">
{{trans('navigation.my-route')}}</a>

Related

Laravel 8.15.0/Jetstream - How to register new blades x-jet-newblade?

I am just doing my very first steps with Laravel 8 and found a problem that I can not solve.
/var/www/html/laravel/resources/views/dashboard.blade.php:
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<x-jet-welcome />
</div>
If i create a new blade in the same directory (f.e. the form.blade.php) with the same code as above but with <x-jet-subform/> instead of <x-jet-welcome> it should normally redirect to the subform.blade.php which is located under var/www/html/laravel/resources/views/vendor/jetstream/components/subform.blade.php
But if I try to get to that page (after setting a Route at web.php) it says
InvalidArgumentException
Unable to locate a class or view for component [jet-subform].
So I think it's necessary to "register" new blades but I found no way to do that...
The view is already published with
php artisan vendor:publish --tag=jetstream-views
You can register your jetstream blade components in App\Providers\JetstreamServiceProvider.php located in app\Providers folder.
Add the following helper function to the file:
protected function registerComponent(string $component) {
\Illuminate\Support\Facades\Blade::component('jetstream::components.'.$component, 'jet-'.$component);
}
Then use the following snippet in register function to register your jetstream blade components:
public function register() {
$this->registerComponent('subform');
}
Now you can use your custom jetstream component:
<x-jet-subform>
I was dealing with the same problem here and found your question unanswered.
The solution I found was to create my own new Blade component.
You can do that using:
$ php artisan make:component MyComponent
This will create two new files /resources/views/components/my-component.blade.php and /app/View/Components/MyComponent.php.
Now you just need to build your component on that blade file and reference it using the x-tag like this:
<x-my-component></x-my-component>
This is how the blade component code should look like
<button {{ $attributes->merge(['type' => 'button', 'class' => 'some-classes']) }}> {{ $slot }} </button>
Hope it helps. Greetings from Brazil :)
I am not sure whether it's the correct or intended way to add new custom x-jet components here as this method may not survive an update, but you can register new components in this file:
vendor/laravel/jetstream/src/JetstreamServiceProvider.php.
Add, $this->registerComponent('subform'); to the configureComponents method, and then call it with an <x-jet-subform> tag

Laravel 5.6 - A shared name for route resources

While creating an admin menu, i was wondering how to set active class item. The menu item have to stay active if the controller is showing, editing or doing something else.
sidebar.blade.php
<li class="nav-item">
<a class="nav-link {{ (Route::current()->getName() == 'posts' ? 'active' : '') }}" href="/admin/posts">Posts</a>
</li>
routes/web.php
// POSTS
Route::resource('/admin/posts', 'Admin\PostController');
How to set a shared name for all resources (index, create, show, etc.)?
I was hoping to do something like this but...
Route::resource('/admin/posts', 'Admin\PostController')->name('posts');
Thanks
Naming Resource Routes
By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:
Route::resource('photos', 'PhotoController')->names([
'create' => 'photos.build'
]);
You can find more options in the documentation.
work in laravel 9 try in other version
Route::resource('vente', VenteController::class,
['names'=>['index'=>'vente.index']]);
call it in menu
vente

Route not defined php laravel5.5

I got an error : Route [admin/news] not defined I try to use #component in my create.blade.php
In my Controller I declare variable
public $route = 'admin/news' ;
In web.php
Route::post('admin/news/create', 'Admin\NewsController#store');
Route::resource('admin/news', 'Admin\NewsController');
In my html this return right Url
<a class="btn btn-success" href="{{ asset($route.'/create') }}">add</a>
<a class="btn btn-success" href="{{ route('news.create') }}">add</a>
I check my route by using php artisan r:l
It has a news.create
I try to use other routes both of these work fine not sure what's wrong with my create route
route('news.edit',$t->id)
route('news.destroy',$t->id)
the problem is in my create.blade.php I try to use #component by this
#component('layouts.submitform',
['id'=>'create','method'=> isset($edit) ? 'PUT' : 'POST' ,'action'=> isset($data->id) ? asset($route.'/'.$data->id) : route($route)]
)
You have $route set to admin/news. You say you want to go to the create page. You then say that the route is named news.create. So use news.create as the name when referencing it with the helper. Set $route to news.create.
You seem to want to use a URI and a route name. You have to decide which one you are going for.
Laravel Docs - Routing - Named Routes
Laravel Docs - Helpers - Url Helpers - route

Laravel 5.3, replace pagination links (<< and >>) with images

How do I replace the custom laravel pagination with images?
I would also like to get the next set of data without reloading the page.
My controller looks like this.
class HomeController extends Controller
{
public function index()
{
$featured_products = DB::table('products')
->where('feature_type','=',3)
->orderBy('created_at','DESC')
->simplePaginate(4);
$latest_products = DB::table('products')
->orderBy('created_at','DESC')
->simplePaginate(4);
return View::make('pages.home')
->with(['featured_products'=>$featured_products,'latest_products'=>$latest_products]);
}
}
The easiest way would be to just edit the blade file for the pagination.
Firstly, in your console run:
php artisan vendor:publish --tag=laravel-pagination
Then go to resources/views/vendor/pagination/default.blade.php and you'll see:
#if ($paginator->onFirstPage())
<li class="disabled"><span>«</span></li>
#else
<li>«</li>
#endif
...
#if ($paginator->hasMorePages())
<li>»</li>
#else
<li class="disabled"><span>»</span></li>
#endif
You can just replace the « and » with the images you want to use.
https://laravel.com/docs/5.3/pagination#customizing-the-pagination-view
Hope this helps!
In 5.3 you can customize pagination views.
In other versions you can try to override this with CSS or you could try to show links manually instead of using $results->render() method:
$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (Not available when using simplePaginate)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (Not available when using simplePaginate)
$results->url($page)

Phalcon PHP - Get Controller Name in View

I have a Site Layout with a top nav bar, I need to set the class to active depending on the controller which changes when the user clicks on different pages.
views->index.phtml
<li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'about') ? 'active' : '' ?>'>About Us</li>
<li class='<?php echo (isset($this->controllerName) && $this->controllerName == 'services') ? 'active' : '' ?>'>Member Sevices</li>
I was hoping that Phalcon had a view function or maybe something I can put in the bootstrap so it worked for all pages with out me having to remember to set the controllerName variable in each Controller manually.
Inside your view access your router service :
$this->router->getControllerName()
$this->router->getActionName()
or if you are using volt you can use the short hand
router.getControllerName()
router.getActionName()
That will work for your use case, but if you find that your menu logic becomes too unwieldy, there are several methods to achieve what you are attempting to do.
The easiest I find is to use javascript, but that doesn't have a fallback if they have js disabled(1%). If you want to cover 100% of your audience you could use a method like the Phalcon team did in INVO using an element library: https://github.com/phalcon/invo/blob/master/app/library/Elements.php

Categories