How to use Laravel routes with a column other than id and query another column too

47 Views Asked by At

I want to build a Laravel route which uses a booking number in the URL and not the row id.

As the booking number column is not unique, I also want to pull the row that also matches the company id field, data pulled from a function in a helper file.

Effectivelly I want to run a very basic SQL WHERE statement along these lines

WHERE number = $number AND company_id = Helpers::companyInfo()->id;

At the moment I have the basics, but I'm struggling to move on.

(web.php)

Route::get('/bookings/{number}', function(Booking $number){
    return view('bookingsView', ['booking' => $number]);
})->name('booking.view');

Thanks in advance.

2

There are 2 best solutions below

0
Karl Hill On BEST ANSWER

You can modify your route closure to accept the booking number as a parameter, and then use the where method on the Booking model to retrieve the booking with the specified number and company id.

use App\Models\Booking;
use Illuminate\Support\Facades\Route;

Route::get('/bookings/{number}', function($number){
    $company_id = Helpers::companyInfo()->id;
    $booking = Booking::where('number', $number)->where('company_id', $company_id)->firstOrFail();

    return view('bookingsView', ['booking' => $booking]);
})->name('booking.view');
0
ElPepito On

As you catch the $number (that is not the primary key) you cannot use the implicit find function used by model typeHint binding. You should construct the function yourself to retreive the booking record. A possible way to do this below :

function(string $number){
       $booking = Booking::where('number', $number)
          ->where('company_id', Helpers::companyInfo()->id)
          ->firstOrFail();
       return view('bookingsView', ['booking' => $number]);
    }