skip to Main Content

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

Answers


  1. 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 AppModelsBooking;
    use IlluminateSupportFacadesRoute;
    
    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');
    
    Login or Signup to reply.
  2. 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]);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search