1

I want to pass data from my controller to blade view. What am I missing?

Controller:

    public function getRolesFront(){

        $roles= Role::join(
        'user_roles',
        'roles.id', 
        '=', 
        'user_roles.role_id')
        ->join(
        'users', 
        'user_roles.user_id',
        '=',
        'users.id')
        ->select(
        'user_roles.id AS row_id',
        'user_roles.user_id',
        'roles.name AS name',
        'roles.function AS function',
        'users.name AS user_name',
        'user_roles.role_id')
        ->orderBy('user_roles.user_id')
        ->get();

        return view('users_view', compact($roles));
    }

web.php

Route::get('/userslist','RoleController@getRolesFront');

blade

<tr>
  @foreach($roles as $role)
  {{$role->role_id}}
  @endforeach
</tr>

the error is:

Undefined variable: roles (View: C:\laragon\www\ProjectoFinal\resources\views\users_view.blade.php)

1 Answer 1

4

When using compact, don't add the actual variable, but rather the string name of the variable that was defined previously in code.

So, not:

return view('users_view', compact($roles));

but rather:

return view('users_view', compact('roles'));
Sign up to request clarification or add additional context in comments.

2 Comments

do you know how do I send another object to the same view, from a different controller?
Sure, in the same way - create a method in that other controller, and within that method, store whatever you like in the same $roles variable, and use the exact same return statement as above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.