I have the following function in my Laravel 9 application:
Route::get('/update-appointment-status/{uuid}/{status}', [App\Http\Controllers\LeadController::class, 'updateAppointmentStatus'])->name('update-appointment-status');
public function updateAppointmentStatus(Request $request, LeadService $leadService, string $uuid, int $status)
{
$validation = $request->validate([
'uuid' => ['required', 'uuid'],
'status' => ['required', 'numeric', Rule::in(Lead::STATUSES)],
]);
$lead = Lead::where('uuid', $uuid)->firstOrFail();
$leadService->updateStatus($lead, $status);
return view('leads.update-status')->with(compact('lead'));
}
The link is accessed from inside emails, which means there is no "previous page". How can I display the error messages inside my view? Right now the app gets redirected to the base URL where there is a validation error.
One solution is to create a "Form Request Validation", you can learn on how to implement this using the Laravel documention: https://laravel.com/docs/9.x/validation#form-request-validation
Then after you created you form request validation, you can define the redirect URL using the $redirect
property and put it inside your form request validation: https://laravel.com/docs/9.x/validation#customizing-the-redirect-location
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SomeRequest extends FormRequest
{
/**
* The URI that users should be redirected to if validation fails.
*
* @var string
*/
protected $redirect = '/path-to-page';
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'uuid' => ['required', 'uuid'],
'status' => ['required', 'numeric', Rule::in(Lead::STATUSES)],
];
}
}