Omer Farooq
Omer Farooq

Reputation: 4064

Best way to run some codes on certain controllers - Laravel 5

I am working on a project that has a control panel with a topbar that contains details about the user like username, email, image url etc. This topbar runs on almost all control panel views. Right now in every controlpanel controller i do something like this

/***** PostController *********/
class PostController extends Controller
{
    protected $user;

    public function __construct()
    {
        $user = Auth::user(); // Note: here $user is not a global variable

        $this->user['user_name']  = $user->name;
        $this->user['user_email'] = $user->email;
        $this->user['user_role']  = $user->getRolesName()->first();
        $this->user['user_image'] = $user->image;
    }

Then in the index controller i would pass the current user with role, and the posts details like this.

 public function index()
    {
        $user = $this->user;
        $posts = json_decode( Post::with('author')->get()->toJson() );
        return view('globaladmin.posts.viewposts',compact('posts'), $user);
    }

I think there might be a much better way of doing this (maybe a design pattern like repository), Like always any help would be appreciated.

Upvotes: 2

Views: 103

Answers (2)

Mohamed Mo Kawsara
Mohamed Mo Kawsara

Reputation: 4688

Since you got simple data to share, I advice you to use Service Injection simply add this code snippet to you master blade template:

@inject('user', 'App\User')

then use $user in every template that extending the master one:

<div>
    Username: {{ $user->user_name }}.
    ...etc
</div>

btw: you don't have to share this since inside auth() global function you've access to you current logged in user like so:

auth()->user()->name // or ->email maybe!

Upvotes: 1

Daniel Wade
Daniel Wade

Reputation: 46

You can use something called a view share. If you look at the documentation (http://laravel.com/docs/master/views#sharing-data-with-all-views) you'll be able to create a service provider that you can place your code in.

A quick (potentially dirty) fix is to use app\Http\Controllers\Controller.php like so:

public function __construct()
{
    $user = Auth::user(); // Note: here $user is not a global variable
    $global_user = [];

    if ($user !== null) {
        $global_user['user_name']  = $user->name;
        $global_user['user_email'] = $user->email;
        $global_user['user_role']  = $user->getRolesName()->first();
        $global_user['user_image'] = $user->image;
    }

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

Edit: to use this in blade, something like this will work:

@if($global_user)
    {!! $global_user->user_name !!}
@endif

Upvotes: 2

Related Questions