1
votes

I have a few vars in my app that I would like to share through multiple views and requests. Basically I have a custom Layout which I load like that:

@section('stylesheet')
    {{ HTML::style(URL::to('custom_stylesheet/'.$slug)) }}
@stop  

I somehow have to send the "slug" var to every request and action and/or controller I need and I need a few. It's a shop from a startpage to checkout, last step.

How can I achieve that? Is View::share() a solution or a cookie?

The URL structure is like that:

www.domain.tld/name/{client_slug}/{event_slug}/<all other variables>  

like /overview or /checkout or /details/{event_id}

Thanks!

2

2 Answers

2
votes

If you need to specify views, use a View Composer:

View::composer(['view-a', 'view-b'], function($view)
{
    $client_slug = 'whatever you need to do to calculate the slug';

    $view->with('client_slug', $client_slug);

    $view->with('event_slug', $event_slug);

    $view->with('variable1', $variable1);
});

Or, as you said, View Share to share with all of them:

View::share('client_slug', $client_slug);

You can create a file for this purpose, something like app/composers.php and load it in your app/start/global.php:

require app_path().'/composers.php';

And you can consider using Session vars too, which keeps data through multiple requests:

Session::put('client_slug', $client_slug);

And get it with

$client slug = Session::put('client_slug');

But if this is a View thing only, View Composers are the way to go.

Using Session and View Composer them togheter is simple, you can set in one request:

Session::put('client_slug', $client_slug);

And in the next request you can send it to your views:

View::composer(['view-a', 'view-b'], function($view)
{
    if (Session::has('client_slug'))
    {
        $view->with('client_slug', Session::get('client_slug'));
    }
    else
    {
        $view->with('client_slug', 'default-slug-or-whatever-you-would-do');
    }
});
0
votes

I'm pretty sure you can do this:

if (Cache::has('slug'))
{
    View::share('slug', Cache::get('slug'););
}

Then just place that in your route file, or perhaps your base controller constructor, where ever you want it.

Then when you first get given the slug:

Cache::put('slug', $slug, 60); //60 minutes