1

I'm working with Laravel 8 and I have made a table like this at Blade:

<div class="card-body table-responsive p-0">
    <table class="table table-hover">
        <tr>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Actions</th>
        </tr>
        @foreach($roles as $role)
            @if(count($role->users))
                @foreach($role->users as $user)
                    <tr>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                        <td>{{ $role->name }} | {{ $role->label }}</td>
                        <td>
                            <form action="{{ route('levels.destroy'  ,$user->id) }}" method="post">
                                @method('DELETE')
                                @csrf

                                <div class="btn-group btn-group-xs">
                                    <a href="{{ route('levels.edit' ,$user->id) }}"  class="btn btn-primary">Edit</a>
                                    <button type="submit" class="btn btn-danger">Delete</button>
                                </div>
                            </form>
                        </td>
                    </tr>
                @endforeach
            @endif
        @endforeach
    </table>
</div>  
    

And the result perfectly showing up:

enter image description here

But now I got problem with Edit & Delete buttons that I have specified $user->id as parameter for both of them.

And when I hover over the buttons I can see the user id properly defined:

enter image description here

But when it comes to edit method which is using Route Model Binding, it does not find the user:

public function edit(User $user)
    {
        dd($user->id); // return null
    }

However if I do not use Route Model Binding and say this instead:

public function edit($id)
        {
            dd($id); // return 1
        }

It properly shows the user id!

I don't know why the Route Model Binding not working here, so if you know what's going wrong or how to fix this issue, please let me know...

memite7760
  • 69
  • 9

2 Answers2

0

You are trying to access the User Model which in this case doesn't know what id is, so you should be passing the id of the user to the edit route using either Get by passing it to the url endpoint , so now you can get it like

public function edit($id)
    {
        dd($id); // return null
    }

or by sending it as a POST form and get it like

public function edit(Request $request)
    {
        dd($request->id); // return null
    }
0

I saw comments, your resource controller name is not matching with your variable name "$user".

You can look here on official laravel docs.

In your situation, this might help;

Route::resource('levels', LevelController::class)->parameters([
    'levels' => 'user'
]);
Alper
  • 152
  • 1
  • 7