mercredi 4 novembre 2015

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.

Aucun commentaire:

Enregistrer un commentaire