Search code examples
phpregexlaraveladminlte

Using regex to make menu item active in laravel adminlte


2021: This was in fact an issue with the package. Regex link matching has since been implemented with the solution I created to solve it for myself. You can read about it in the documentation here.


I'm using Laravel 5.8 with AdminLTE for Laravel.

There's several options to create a menu, one of which is to create it in the provided config file, which I use.

You can specify an active key in the menu that allows you to make the menu have the class that makes the menu item active and activates the dropdown.

I have a menu item, which I would like to make active on these pages:

  • /posts (works with active => ['/posts'])
  • /posts/{post_id} (id are only numbers)

These URL's shouldn't match:

  • /posts/create
  • /posts/anyotherlink
  • /posts/1text

I can not use /posts/* because that would make the create page and some others active.

The readme suggest that you can also use regex to do this. I don't use regex at all, but I came to this, which, according tot regex101 seems to match what I need it to:

^\/posts\/[0-9]+$

I've tried to implement it like so:

[
    'text'    => 'Posts overview',
    'url'     => '/posts',
    'icon'    => 'list',
    'active'  => ['/posts', '^\/posts\/[0-9]+$'],
    'active'  => ['/posts', '/posts/[^0-9]'] // also tried this
],

Unfortunately, this does not seem to work as it doesn't make the menu item active on the pages listed above.

Edit: I've also created an issue in the GitHub repository as I suspect that this might be an issue with the package.

Am I missing something, or doing something wrong?


Solution

  • In the ActiveChecker.php class of the project you can find this piece of code

    protected function checkPattern($pattern)
    {
        $fullUrlPattern = $this->url->to($pattern);
    
        $fullUrl = $this->request->fullUrl();
    
        return Str::is($fullUrlPattern, $fullUrl);
    }
    

    Based on laravel documentation, Str::is does not run regexp matching, but justs supports asterisks for wildcards.

    In your case you could post a PR that will use regexo if the given pattern is a regular expression, otherwise, run Str::is