I have a GET route with wildcard Date.
The day wildcard is a string as follows: 20220507 (YYYYMMDD).
After validating the string I want a correct response. Before sending the response I want to verify the string length and format.
My question is, is it possible to validate the string using Illuminate\Foundation\Http\FormRequest or Illuminate\Http\Request Production: Request? Or do they only accept publishing requests?
Code:
php artisan make:request CalendarDayRequest
Example of getting routes in web.php
Route::get('/calendar/{day}' , 'App\Http\Controllers\HomeController@calendar')->name('calendar');
Sample Controller
use App\Http\Requests\CalendarDayRequest; public function calendar ( CalendarDayRequest $request ) { // Code }
Or sample controller 2
use Illuminate\Http\Request; public function calendar ( Request $request ) { $validated = $request->validate([ 'day' => 'required', ]); }
I'm getting the error: Infinite redirect loop, too many redirects.
P粉7060387412024-03-28 09:30:04
First, you cannot validate route parameters in form requests
However, you can use regular expressions to validate your routes Example:
Route::get('/calendar/{day}', 'App\Http\Controllers\HomeController@calendar')
->name('calendar')
->where('day', '/^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$/');
If you still want to use validate()
function or form request
$request->merge([
'day' => $day
]);
$this->validate($request, [
'day' => 'date_format:Ymd',
]);
Form request method - override all()
method
public function all($k = null){ $data = parent::all($k); $data['day'] = $this->route('day'); return $data; }
If that doesn't work, try the following code
public function calendar(Request $request, $day){ $data = $request->all(); $data['day'] = $day; $validator = Validator::make($data, [ 'day' => 'required|date_format:Ymd', ]); if($validator->fails()){ // Do Something abort(404); } }
How to verify routing parameters in Laravel 5?
But if you want to use the validate()
function, I recommend you send it as a request parameter.