Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Laravel 5.4 toggle sidebar state with AdminLte using Ajax and Sessions

David Carr

Laravel Framework PHP & MySQL

AdminLte is a great Admin theme, one feature that’s really good is being able to toggle the sidebar open and closed but this state does not remain from page to page, wouldn't it be great that when you closed the sidebar it stays closed? 

In this post, I’ll show you how to save its state.

First, add an id of sidebarToggle (you can use the class if you prefer) to the toggle a link. This will be used to detect each time the toggle is clicked on.

<li><a href="#" id='sidebarToggle' class="sidebar-toggle" data-toggle="offcanvas" role="button">
    <i class="fa fa-bars"></i>
</a></li>

Setup an ajax listener, this will fire an ajax request each time the toggle is clicked.

$('#sidebarToggle').on('click', function(e) {
    $.ajax({
        type: "POST",
        url: "{{ url('dashboard/savestate') }}"
    });
});

A post route is now required:

Route::post('savestate', 'DashboardController@saveState');

Now in the controller check if there is a session called sidebarState if there is remove it otherwise set the value of ‘sidebar-collapse’ this will be used on the layout.

public function saveState()
{
    //if no session then save as colaped
    if (Session::has('sidebarState')) {
        Session::remove('sidebarState');
    } else {
        //colapse sidebar
        Session::put('sidebarState', 'sidebar-collapse');
    }
}

Now back in the layout on the body tag pass in the session:

<body class="skin-black sidebar-mini {{ Session::get('sidebarState') }}">

Now every time the toggle is clicked its state will be preserved for the lifetime of the session.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.