Farshad
Farshad

Reputation: 2000

how to get the current id of show function in laravel

in my controller in my show function in laravel i want the get the id that shows in browser show when i browse it it shows like this

http://localhost:8000/admin/invoices/1

i want to get that "1" and use it in show controller like below

public function show(Invoice $invoice)
{
    $clients = Invoice::with('user','products')->get();
    $invoice_id = 1;
    $invoices = Invoice::with('products')->where('id', '=', $invoice_id)->firstOrFail();
    return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}

and put it instead of $invoice_id so when every my client visit this page only sees the related invoice products . thanks you for help

Upvotes: 0

Views: 6627

Answers (3)

Cesar Devesa
Cesar Devesa

Reputation: 1307

Usually happens when giving a route name different from the controller name

Example:

Route::resource('xyzs', 'AbcController');

Expected:

Route::resource('abcs', 'AbcController');

Upvotes: -1

Jonathon
Jonathon

Reputation: 16293

If you're actually getting an instance of Invoice passed to your show method then it likely means you have Route-Model Binding set up for your project. Laravel is looking at the defined route and working out that the ID part (1) should map to an instance of Invoice and is doing the work to grab the record from the database for you.

The Invoice object passed through should refer to an item in your database with the ID of 1, so to get the ID that was mapped in the route you can simply just do:

public function show(Invoice $invoice)
{
    echo $invoice->id; // This should be 1

Laravel supports route model binding out of the box these days, but in earlier versions you had to set it up in app/Providers/RouteServiceProvider.php. If you don't want it, try replacing your show method signature with this:

public function show($id)
{
    echo $id; // Should be 1

By removing the type-hint you're simply expecting the value that was given in the route parameter and Laravel won't try to resolve it out of the database for you.

Upvotes: 3

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

Try using $invoiceId

public function show(Invoice $invoice, $invoiceId)
{
    $clients = Invoice::with('user','products')->get();
    $invoices = Invoice::with('products')->findOrFail($invoiceId);
    return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}

Upvotes: -1

Related Questions