Reputation: 10105
I had some original code that shows like below with form validation and saving process in MySQL Database.
Original Code
public function store(Request $request)
{
$v = \Validator::make($request->all(), [
'Category' => 'required|unique:tblcategory|max:25|min:5'
]);
if ($v->fails()) {
return \Redirect::back()
->withErrors($v)
->withInput();
}
...
//code to save the record in database is here....
...
}
Then I followed this article and modified the above function and now it looks like below.
public function store(CategoryRequest $request)
{
...
//code to save the record in database is here....
...
}
and below is the Request class
class CategoryRequest extends Request
{
protected $redirect = \Redirect::back()->withErrors($v)->withInput();
public function authorize()
{
return false;
}
public function rules()
{
return [
'Category' => 'required|unique:tblcategory|max:25|min:5'
];
}
}
Error Details
syntax error, unexpected '(', expecting ',' or ';'
This error is coming at below line.
protected $redirect = \Redirect::back()->withErrors($v)->withInput();
Am I missing something ?
Upvotes: 4
Views: 11261
Reputation: 2303
In Laravel 8 the above has changed, so the response
function did not work for me, getRedirectUrl
on the other hand did. Here's a code snippet
protected function getRedirectUrl()
{
$url = $this->redirector->getUrlGenerator();
return $url->previous();
}
Upvotes: 0
Reputation: 961
There are multiple ways to tell Laravel what to do when validation fails. One method is to overwrite the response() method and set your own response as follows...
class CategoryRequest extends Request
{
public function response(array $errors){
return \Redirect::back()->withErrors($errors)->withInput();
}
public function authorize()
{
return false;
}
public function rules()
{
return [
'Category' => 'required|unique:tblcategory|max:25|min:5'
];
}
}
Laravel's default response is to redirect you to the previous page with errors and input values so the above code is probably not required in your case.
Upvotes: 8