We can get session value or data of a loginned user at AppServiceProvider. The following we will show how to get, share values of session and loginned user to all views.
=========
Code:
namespace App\Yourapp\Younamespace;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\View;
use App;
class AppServiceProvider extends ServiceProvider{
public function boot() {
$auth = $this->app['auth']; // get Laravel's Auth facades
view()->composer('*', function($view) use (&$auth) { // this function coding style is php callback and you can pass variables at boot() to this callback function.
$user = $auth->user(); // get the loginned user
if ( empty(Session::get('sessionDataWithAssignedKeyYouWant', '')) {
Session::put('sessionKeyYouWant', 'sessionDataYouWant'); // set session data
}
$mySessionDataWithAssignedKey = Session::get('sessionKeyYouWant', 'sessionDataYouWant'); // get session data
$view->with(['user'=> $user, 'myVariable' => $mySessionDataWithAssignedKey]); // share these values to all views.
});
}
public function register() {
}
}
You can change the first parameter at view()->composer()
from star sign to what you want. For example, user.* means all views under user directory or this way *.checkout means all view directories has named checkout view. But when you change from star sign to what you want view, you should rather to get and set session data in middleware instead of do them in AppServiceProvider.
Enjoy it.