jacobdo
jacobdo

Reputation: 1615

Passing data to all views served by a controller in Laravel

I have a controller that has two methods, each serving up a different view:

class NavController extends Controller {
 public function posts()
 {
  $posts = Post::all();
  $tabs = Tag::all();
  return view('posts')->with('posts', => $posts, 'tags' => $tags);
 }
 public function users()
 {
  $users = User::all();
  $tabs = Tag::all();
  return view('users')->with('users', => $users, 'tags' => $tags);
 }
}

I wish to avoid writing the logic for retrieving and passing tags in each and every method and thus I am wondering if there is a way to retrieve the data in one place in the controller and then pass it by default to every view that is served up by this controller.

I think it is worth mentioning, that I DO NOT want to share this data across all views, so that for example, I could use the tags variable in different controllers to serve tags based on a different logic.

Upvotes: 1

Views: 353

Answers (1)

Metalik
Metalik

Reputation: 943

Use View::share on the class construct function:

use View;

class NavController extends Controller {
    function __construct() {
        View::share('tags', Tag::all());
    }
    public function posts()
    {
        $posts = Post::all();
        return view('posts')->with('posts', => $posts);
    }
    public function users()
    {
        $users = User::all();
        return view('users')->with('users', => $users);
    }
}

Upvotes: 1

Related Questions