简体   繁体   中英

How do i use one to many relationship within Laravel 8 Middleware?

I have a Users and Roles table in my database. One user can have many roles . I am using Laravel 8, I want to be able to return all roles for that user within the middleware (I am using inertia.js - handleinertiarequest.php ).

Roles Table:

id role user_id
1 super_admin 3
2 admin 3
3 user 3

Users Table:

id name
1 Some name
2 Some other name
3 Joe Bloggs

User Model ( User.php ):

public function userroles()
{
    return $this->hasMany(Roles::class);
}

Roles Model ( Roles.php ):

public function user()
{
    return $this->belongsTo(User::class);
}

HandleInertiaRequest.php :

public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'auth' => function () use ($request) {
            return [
                'user' => $request->user() ? [
                    'id' => $request->user()->reference,
                    'first_name' => $request->user()->first_name,
                    'last_name' => $request->user()->last_name,
                    'role_staff' => \App\Models\Roles::select('id'),
                ] : null,
            ];
        },
    ]);
}

Layout.vue :

{{ $page.props.auth.user.role_staff }}

So if I am logged in as Joe Bloggs ( id = 3 ), I want it to return 3 roles (or even just 1, if using the id ). But this doesn't return anything or show any errors. What am i missing here? Thanks

Use this relationship method in user modal:

public function userRoles()
{
    $this->hasMany('App\Models\role_table_modal_name','user_id');
}

Then in controller/middleware call your User modal:

$ user_roles = User::find($id)->with('userRoles')->get();

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.

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