I have a project on Laravel 5.7 where I create a custom admin (admin.blade.php) page after login, just adding the column userlevel on my Users table, and I have the next foreach on my admin.blade
admin.blade.php
@foreach($customers as $customer)
<h3><b>{{$customer->count('id')}}</b></h3>
@break
@endforeach
Everything is ok when I do it the login on my page, but IF I close the page and I try to open again with the URL (example: http://192.168.1.125:8010/ ) the project show me the next error:
Undefined variable: customers (View: D:\ExamplePage\system\resources\views\admin.blade.php) Undefined variable: customers (0)
routes/web.php
Route::get('/', function () {
if($user = Auth::user())
{
if(Auth::user()->userlevel == "admin"){
return view('/admin');
}
}
return view('/auth/login');
});
Route::get('/admin', 'HomeController@index')->name('admin');
HomeController.php
use App\customers;
use App\pawns;
public function index()
{
$customers = customers::all();
$pawns = pawns::all();
return view('admin', compact('customers'), ['customers' => $customers,'pawns'=>$pawns]);
}
RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ($guard == 'admin') {
return redirect()->route('/admin');
}
}
return $next($request);
}
How can I solve to everything that I open again the URL, this show me the admin.blade.php if I logged and dont show me the error with the variable $customers
Thanks
That is because it unable to customer variable, compact is php function to merge array, and third parameter is used to merged Data, you don't need to pass a third parament, Instead Update the code in your home controller like this.
use App\customers;
use App\pawns;
public function index()
{
$customers = customers::all();
$pawns = pawns::all();
return view('admin',['customers'=>$customers,'pawns'=>$pawns]);
Or
return view('admin',compact('customers','pawns'));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.