Search code examples
laraveladminlaravel-nova

Laravel Nova multiple resources for same user model


I have a laravel + nova project.

Currently I have a USER model, with 'admin' column, with values 0 or 1.

I use this model for nova dashboard login.

Now, I want to separate admin users and normal users in nova dashboard. Like showing two Resources 1 ) Admins 2 ) Users at left side in nova dashboard.

Can I user same User model for two resources?

Currently it is showing two resources with names Admins and Users, but both opens admin list all time. Not the users list at all.

Thanks


Solution

  • Since Admins and Users are not separate users in your case, consider using Filters instead for your User resource.

    To answer your question, if you want to stick to your implementation of 2 Nova resources for Admin and User respectively, you can add override the index query that is made to your Nova resource. To override this behaviour, add the following code to the Nova resource:

    App\Nova\Admin.php

    /**
     * Build an "index" query for the given resource.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function indexQuery(NovaRequest $request, $query)
    {
        return $query->where('admin', 1);
    }
    

    And the following code to

    App\Nova\User.php

    /**
     * Build an "index" query for the given resource.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function indexQuery(NovaRequest $request, $query)
    {
        return $query->where('admin', 0);
    }
    

    Note: with the above solution users can still manually navigate to yourwebsite.test/nova/resource/admins/{id}. Consider adding Authorization, so users can't view admins for example (depending on your use case).