Reputation: 139
I am trying to pass data to a view using the boot method in the AppServiceProvider
, and have followed the steps outlined in one of the Laracast fundamentals videos. However, I am getting an error in my controller when trying to use this variable.
In my AppServiceProvider:
public function boot()
{
view()->composer('home', function($view){
$view->with('current', Post::orderBy('created_at', 'desc')->first());
});
}
So this should pass the data to my home view as far as I understand, so that I don't need to keep referencing it in all the methods I have in the controller for that view. I then have a homeController with the following method:
public function index()
{
//Get user
$user = Auth::user();
//OMDB API setup - Get Movie name, remove spaces, add into API request
$movie_one = str_replace(" ", "+", $current->movie_one);
$movie_two = str_replace(" ", "+", $current->movie_two);
return view('home', compact(array('user')));
}
Previously I was adding a variable called current
in this method to get an entry from my Post
table, but wanted to add it to the AppServiceProvider
as I will have to re-declare it in other methods as well. The issue I have is that I try to use the $current
object again in this method, but it isn't available to it? I get the following error:
ErrorException in homeController.php line 30:
Undefined variable: current
What can I do here? Can I pass that data from to a controller as well as the home view? Or is that not possible?
Upvotes: 0
Views: 799
Reputation: 5135
the code you written inside the boot
method, will only be accessible inside home view, if you want to access the Post object
inside controller too, you have to follow this, through this you can access your Post
object in controller, as will as view.
app()->singleton('current',function($app){
return Post::orderBy('created_at', 'desc')->first();
});
So in your code, you can access the Post
object like this,
$post_obj = App::make('current');
$post_obj->movie_two;
or directly
App::make('current')->movie_two;
Upvotes: 1