skip to Main Content

I want to display user which have particular id. For example for id 1 should display customer which have id 2. Now redirect me to customers/1 but show empty page. What can I do that display user ?
route

Route::get('/', function () {
    return redirect()->route('customers.index');
});
Route::get('/customers', 'AppHttpControllersCustomerController@index')->name('customers.index');
Route::get('/{id}', 'AppHttpControllersCustomerController@show')->name('customers.show');

controller

public function show(Customer $customer)
{
    return view('show', compact('customer'));
}

view customers

a href=" {{ route('customers.show', ['id' => $customer->id]) }} ">

view customers/1

<tr>
<td>{{ $customer->first_name }}</td>
<td>{{ $customer->last_name }}</td>
<button type="submit" class="btn btn-danger">Delete</button>
<button type="submit" class="btn btn-success ms-1">Updated</button>
</tr>

2

Answers


  1. Route: you can customize the route as you like, but the standard is as follows:

    Route::get('/customers/{customer}', 'AppHttpControllersCustomerController@show')->name('customers.show');
    

    CustomerController: when you do route model binding, it will do the findOrFail, so if you pass a customer that doesn’t exist, you will get a 404 error automatically.

    public function show(Customer $customer)
    {
        return view('customers.show', compact('customer'));
    }
    

    customers.show view: basic view to show data compacted from the controller

    <tr>
       <td>{{ $customer->first_name }}</td>
       <td>{{ $customer->last_name }}</td>
    </tr>
    

    Simple, yet elegant 🙂


    You can read how laravel prefers to structure routes here: https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller

    You can also go 1 step further, and let laravel do everything for you with the simple artisan command:

    php artisan make:model Customer -mcr
    

    Which will create, a resource, a migration, and a full resource controller.

    Then in your web.php route:

    Route::resource('customers', 'CustomerController');
    
    Login or Signup to reply.
  2. Try change you code in routes file to:

    Route::prefix('/customers')->group(function () {
        Route::get('/customers', 'AppHttpControllersCustomerController@index')->name('customers.index');
        Route::get('/{id}', 'AppHttpControllersCustomerController@show')->name('customers.show');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search