5. Setting the active theme

Giannis Gasteratos edited this page Apr 27, 2018 · 7 revisions

Working with themes is very straightforward. Use:

Theme::set('theme-name');        // switch to 'theme-name'
Theme::get();                    // retrieve current theme's name
Theme::current();                // retrieve current theme (insance of Igaster\LaravelTheme\Theme)
Theme::exists('theme-name');     // Check if 'theme-name' is a registered theme

You should set your active theme on each request. A good place for this is a Middleware. You can even define the Theme inside your Controller, before returning your views.

You can optional set a default theme in the theme.php configuration file, which will be activated during application bootstraping.

Using a Middleware to set a theme

A helper middleware is included out of the box if you want to define a Theme per route. To use it:

First register it in app\Http\Kernel.php:

protected $routeMiddleware = [
    // ...
    'setTheme' => \Igaster\LaravelTheme\Middleware\setTheme::class,

Now you can apply the middleware to a route or route-group. Eg:

Route::group(['prefix' => 'admin', 'middleware'=>'setTheme:ADMIN_THEME'], function() {
    // ... Add your routes here 
    // The ADMIN_THEME will be applied.

Example: Let the user change the theme

Scenario: You have a theme switcher and when the user clicks on a theme, then he hits a route and the theme is applied on the whole application, for all the subsequent requests.

Note: This is just a boilerplate to help you get started. You may need to adapt it to your needs...


Route::get('/change-theme/{theme-name}', 'themeController@changeTheme');


public function changeTheme($themeName)
        session(['theme-name' => $themeName);
        return redirect()->back();

Set the theme on a custom middleware

First create your middlware. ie: artisan make:middleware SetThemeFromSession

Then in the handle method of your middleware, read the theme name which is stored in the session:

public function handle($request, Closure $next)

Now you need to register your middleware inside the app\Http\Kernel.php file. For example if you want to apply your theme to all your routes, then you should add it into the web array:

    'web' => [
        // ...
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.