简体   繁体   English

更改 laravel 问题中的索引刀片

[英]Changing the index blade in laravel issue

I have following in my laravel web.php我的 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,现在在我家 controller 索引 function 我有以下代码,

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当我在web.php中使用以下路由而不是以前的路由时,主页没有错误并且工作正常

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?我该如何解决这个问题?

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而且您没有使用视图发送必要的数据,在这种情况下$count_apps

You should remove the faulty call to home view and and define it like this:您应该删除对home视图的错误调用,并像这样定义它:

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 .这将从//home获取 url 并将其发送到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您应该在控制器的构造函数中调用auth中间件,这将使您的路由文件更具可读性

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每当调用此 controller 中的 function 时,这将调用auth中间件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM