Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

warpig's avatar
Level 12

How to access a method inside Blade?

I want to access my roles() method because I need to fetch only users with roles, how do I do that?

User.php

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
	@foreach ($users as $roleUser)
		<p>{{ $roleUser->roles()->name }}</p>
	@endforeach

AppServiceProvider.php

    public function boot()
    {
        View::composer(['admin.users.index'], function ($view) {
            $view->with('users', User::with('roles')->get());
        });
    }
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$name
0 likes
1 reply
MichalOravec's avatar
Level 75

roles is a collection, so

@foreach ($users as $user)
    @foreach ($user->roles as $role)
        <p>{{ $role->name }}</p>
	@endforeach
@endforeach

or

@foreach ($users as $user)
    <p>{{ $user->roles->pluck('name')->join(', ') }}</p>
@endforeach
1 like

Please or to participate in this conversation.