Global variable in laravel 4

前端 未结 6 575
萌比男神i
萌比男神i 2020-12-07 23:17

I was wondering how to do a global variable to save me few lines of copy and pasting this lines. Array it probably and put them in one variable instead? I want to use this

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 23:48

    I also gave you the same answer in another question you asked, you did not respond. Link

    There is no reason to have a separate variable for each property of your $provider model. Simply save the entire model to a variable like this.

    if (Auth::check())
    {
        $provider = Auth::user();
    }
    

    This would generally be done in a route like this.

    Route::get('/provider/page/example', function()
    {
        $provider = Auth::user();
    
        return View::make('name.of.view', ['provider' => $provider]);
    });
    

    After having done that, you can access the different properties in of the $provider in your views like this.

    Your email address is: {{$provider->email}} and your first name is {{$provider->first_name}}

    Another option is to use a controller and set this variable only once in the controller, making it accessible from all views using View::share().

    class ProviderController extends BaseController {
    
        protected $provider;
    
        public function __construct()
        {
            $this->provider = Auth::user();
    
            View::share('provider', $this->provider);
        }
    
        public function getIndex()
        {
            return View::make('some.view.name');
        }
    }
    

    After having done just this, you can use the $provider variable in your views as shown above using things like $provider->email. You can also use it elsewhere in the controller by using $this->provider.

提交回复
热议问题