Make a variable accessible from anywhere within the Laravel application

时间:2015-10-29 15:51:32

标签: php laravel laravel-5 laravel-5.1

I make a cURL request to an API

http://site/user


I got back this response

    data: Object
    first_name: "Bob"
    last_name: "Jones"

I grab the first name and last name and concatenate them together and stored into a variable call $name.

$fn = VSE::user('first_name',$username);
$ln = VSE::user('last_name',$username);
$name = ucwords($fn.' '.$ln); // Bob Jones

I want to display this $name on my navigation.

Sending this $name variable with every view would be a little over kill. I'm seeking for a better way of doing this.

What should I do to make that variable accessible throughout my application routes/views ?


Restriction: I don't have the access to the Auth::user object.

3 个答案:

答案 0 :(得分:3)

Use a view composer to make the variables you need available in each view.

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

http://laravel.com/docs/5.1/views#view-composers

view()->composer('*', function ($view) {
    $fn = VSE::user('first_name',$username);
    $ln = VSE::user('last_name',$username);
    $name = ucwords($fn.' '.$ln); // Bob Jones

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

If you didn't want to use a view composer, you could simply add a call to the view()->share() method in your AppServiceProvider boot method

public function boot()
{
    $fn = VSE::user('first_name',$username);
    $ln = VSE::user('last_name',$username);
    $name = ucwords($fn.' '.$ln); // Bob Jones

    view()->share('name', $name);
}

答案 1 :(得分:2)

我不明白为什么你不能把这个名字放在laravel会话或缓存中。

Laravel会话

在会话中设置一个值:

Session::put('key', 'value');

从会话中检索项目:

$value = Session::get('key');

有关详细信息,请参阅http://laravel.com/docs/5.0/session#session-usage

Laravel缓存

设置缓存:

Cache::put('key', 'value', $minutes);

根据缓存值:

$value = Cache::get('key');

有关详细信息,请参阅http://laravel.com/docs/5.0/cache#cache-usage

答案 2 :(得分:0)

try create a static method returning what you want. And in all places you can do for example.

Custom.getName();

See this documentations:

http://php.net/manual/pt_BR/function.forward-static-call.php

or

php static function