I have following in my laravel web.php
Route::get('/', function () { return view('home'); })->middleware('auth'); Route::get('/home', 'HomeController@index');
This would redirect my users back to login page if they are not logged in and logged in users would redirect to home page.
Now In my home controller index function I have following code,
public function index() { $get_customers = User::where('user_roles','=','customer')->get(); $count_customers = $get_customers->count(); $get_apps = Website::all(); $count_apps = $get_apps->count(); return view('home',compact('count_customers','count_apps')); }
When every time i’m trying to access my home page after logged in i’m getting an error saying
$count_apps is undefined
BUT,
When I used following routing in my web.php
instead of previous routing, home page gives no error and works properly
Route::get('/', function () { return view('auth.login'); })
But even though this made my login blade as the index page, every time when I try to access index as an already logged in user it keep redirecting me to the login blade not to he home blade….
How can I fix this issue?
Advertisement
Answer
You are getting this error:
$count_apps is undefined
becuase when you are calling this route:
Route::get('/', function () { return view('home'); })->middleware('auth');
And you are not sending the necessary data with the view which is in this case $count_apps
You should remove the faulty call to home
view and and define it like this:
Route::get('/{name}', array( 'as' => 'home', 'uses' => 'HomeController@index') )->where('name', '(home)?')->middleware('auth');
This will get url from /
or /home
and send it to HomeController@index
.
Now if your website does not allow unauthenticated user to accses any route.
you should call the auth
Middleware in the constructor of the controllers it would make your route file more readable
class HomeController extends Controller { /** * Instantiate a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } }
This will call the auth
Middleware whenever a function in this controller is called