Skip to content

5. Setting the active theme

Ahmad Syamim edited this page Sep 28, 2021 · 9 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 (instance 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:

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

Controller:

public function changeTheme($themeName)
{
    if(Theme::exists($themeName)){
        Theme::set($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)
{
    if(session()->has('theme-name')){
        \Theme::set(session('theme-name'));
    }
}

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' => [
        // ...
        \App\Http\Middleware\SetThemeFromSession::class,
    ],