Error App\Http\Requests\AddUserRequest::fails does not exist - laravel

I get this error when I want to insert data into the table and return a message.
Here is my code.
When I entered the form and submitted, an error occurred: Method App\Http\Requests\AddUserRequest::fails does not exist.
Code In Router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code In UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
{
return redirect('admin.add-user')
-> withInput()
-> withErrors($request);
}else
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
}
}
Code In view:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
#csrf
<div class="form-group">
#if (session('success'))
<div class="alert alert-success">
<p>{{ session('success') }}</p>
</div>
#endif
#if ($errors->any())
<div class="alert alert-danger">
<b>Lỗi!! Bạn vui vòng kiểm tra lại:</b>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
In AddUserRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class AddUserRequest extends FormRequest
{
/**
* 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 [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
];
}
}
Thank you for your help!

you don't need to put that check, because data is already validated through your request
public function getAdd(AddUserRequest $request)
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}

AddUserRequest is a FormRequest it doesn't have fails method. For FormRequest you don't need to check fails, it automatically validate your request data using rules provided in that class and throw validation error, for details check here.
For FormRequest validation you use it like this
public function getAdd(AddUserRequest $request)
{
//all code here executed after validation
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
If you need to check validation in you controller then use manual validation like this.
public function getAdd(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
]);
if($validator->fails())
{
return redirect('admin.add-user')
-> withInput()
-> withErrors($request);
}else
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
}

Related

Livewire validateOnly with validate in the same component

I have a little problem with the data validation with livewire ( laravel ).
I noticed that when I set up the validation in real time ( validateOnly() ), the information entered in the form is validated in real time. At this level everything is fine.
But when I click on the button to submit the form (even though the form contains errors), the form is unfortunately sent to my function defined in the wire:submit.
So my question is : is it possible to revalidate the information in the wire:submit method that receives the data after the form is submitted ? If so, how can I do that?
PS: I tried to set the validate method in my wire:submit function but nothing happens. It blocks the form from being submitted but it doesn't give me an error .
My source code :
<?php
class UserProfile extends Component
{
use WithFileUploads;
public $countries = [];
public $profile = [];
protected function rules() {
if ( !LivewireUpdateProfileRequest::authorize() ) {
return abort(403, "Your are not authorized to make this request !");
}
$rules = LivewireUpdateProfileRequest::rules();
if ( !empty($this->profile['phone']) ) {
$rules['profile.phone'] = [ 'required', 'phone_number:' . $this->profile['phone'] ];
}
return $rules;
}
public function mount()
{
$this->countries = Countries::all();
$this->profile = Auth::user()->toArray();
}
public function updateUserProfile()
{
$validatedData = $this->validate();
dd( $validatedData );
}
public function updated($key, $value)
{
$this->validateOnly($key);
}
public function render()
{
return view('livewire.user-profile');
}
}
Html source :
<form action="" method="POST" wire:submit.prevent="updateUserProfile">
<input name="profile.email" type="email" wire:model="profile.email" />
#error('profile.email') {{ $message }} #enderror
<input name="profile.phone" type="tel" wire:model="profile.phone" />
#error('profile.phone') {{ $message }} #enderror
</form>
Here is LivewireUpdateProfileRequest content :
<?php
namespace App\Http\Requests\Web;
use Illuminate\Foundation\Http\FormRequest;
class LivewireUpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public static function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public static function rules()
{
return [
'profile' => ['required', 'array', 'size:10'],
'profile.firstname' => ['required', 'string'],
'profile.lastname' => ['required', 'string'],
'profile.email' => ['required', 'email'],
'profile.phone' => ['required', 'phone_number:33'],
'profile.gender' => ['required', 'gender'],
'profile.image' => ['sometimes', 'image', 'mimes:png,jpg,jpeg'],
'profile.address' => ['required', 'string'],
'profile.city' => ['required', 'string'],
'profile.country_id' => ['required', 'exists:countries,id'],
'profile.birth_at' => ['required', 'date', 'min_age:18'],
];
}
}
Usually in your saving method you would run validation once more for all fields. The livewire docs share this example:
Livewire Component:
class ContactForm extends Component
{
public $name;
public $email;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function saveContact()
{
$validatedData = $this->validate();
Contact::create($validatedData);
}
}
With this HTML:
<form wire:submit.prevent="saveContact">
<input type="text" wire:model="name">
#error('name') <span class="error">{{ $message }}</span> #enderror
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Save Contact</button>
</form>
This should validate the inputs near-realtime using the updated-method and on submit using the saveContact-method.
If you could share your code, we could debug it easier.
Source: https://laravel-livewire.com/docs/2.x/input-validation#real-time-validation

Validation of Laravel does not show me the errors in the view

I have this in the controller...
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price' => 'required',
'long_description' => 'required'
]);
$product = new Product();
foreach ($request->all() as $key => $value) {
if ($key !== '_token') $product->$key = $value;
}
$product->save();
return redirect('/admin/products');
}
And this in the view...
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{‌{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The form without the validation works perfect. But I do not understand why he does not show me the errors in the view when redirected.
You need to do something like this-
public function store(Request $request)
{
$request->validate($request, [
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price' => 'required',
'long_description' => 'required'
]);
if (!$validator->fails()) {
$product = new Product();
foreach ($request->all() as $key => $value) {
if ($key !== '_token') $product->$key = $value;
}
$product->save();
return redirect('/admin/products');
} else {
\Session::flash('errors', $validator->messages());
return redirect()->back()->withInput();
}
}
I made two changes in your code-
Added validate method on $request instead of $this.
Added a check for failed validation and sent those errors through a session.
I have already solved. The problem was that I had the post route inside api.php. By moving it to web.php it works.

Laravel: Why are validation messages not show?

I use Laravel 5.4 on hosting. My validation method is working, but it doesn't show messages. I do all the needed operations for displaying errors but it doesn't work.
#if($errors->has('recipient'))
<div class="form-group">
<label class="col-lg-2 control-label"></label>
<div class="col-lg-10">
<div class="alert alert-danger">
<ul>
#foreach ($errors->get('recipient') as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
</div>
#endif
I use {{ csrf_field() }} tokens. Validation rules work if wrong user types are used, but messages are not displayed.
My send method:
public function send(Request $request)
{
$this->validator($request->all())->validate();
$this->create($request->all());
return redirect($this->redirectToAfterSendMessage);
}
My validator code:
protected function validator(array $data)
{
return Validator::make($data, [
"$this->recipient" => [
'sometimes',
'required',
'email',
'exists:users,email',
Rule::notIn([auth()->user()->email])
],
"$this->subject" => 'sometimes|required|min:10',
"$this->message" => 'sometimes|required|min:50',
], $this->validator_messages());
}
My routes:
Route::get('/compose', 'InboxController#compose') ->name('compose');
Route::post('/compose', 'InboxController#send');
Result of dump($errors):
ViewErrorBag {#244 ▼
#bags: []
}
EDITED
To fix your current problem, change $errors->get('recipient') to $errors->all().
It should look like this:
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
--
This isn't a direct solution for your question. However an even better approach (imo) than yours are custom requests. You can quickly generate custom requests by using the following command:
php artisan make:request CustomRequest
After that you can change type from Request to CustomRequest
public function send(CustomRequest $request)
{
$this->create($request->all());
return redirect($this->redirectToAfterSendMessage);
}
And in CustomRequest.php your extract your validation logic like so:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CustomRequest extends FormRequest
{
/**
* 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 [
'name' => 'required',
'email' => 'required',
'message' => 'required',
];
}
public function messages()
{
return [
'name.required' => 'Name is required.',
'email.required' => 'Email is required.',
'message.required' => 'Message is required.',
];
}
}
Hope this helps.
You need to change:
"$this->recipient"
"$this->subject"
"$this->message"
To:
'recipient'
'subject'
'message'

what is the correct way of form validation in laravel?

I have just created the form and action is PagesController#check and the validation is as follows:
#extends('layout')
#section('content')
<div class = "container">
{!! Form::open(['action' => 'PagesController#check' , 'method' => 'POST']) !!}
<div class = "form-group">
{{ Form::label('country','Country')}}
{{ Form::text('country','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('age','Age')}}
{{ Form::number('age','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('marks','Marks')}}
{{ Form::number('marks','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
<div class = "form-group">
{{ Form::label('description','Description')}}
{{ Form::textarea('description','', ['class' => 'form-control' , 'placeholder' => ''])}}
</div>
{{ Form::submit('Submit' , ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
And the check() method in the PagesController is like this:
public function check(Request $request){
$this->validate($request, [
'country' => 'required',
'age' => 'required',
'marks' => 'required',
'description' => 'required'
]);
return 123;
}
Why is it then it is throwing the following error:
(2/2) ErrorException
Action App\Http\Controllers\PagesController#check not defined. (View: C:\wamp64\bin\apache\apache2.4.23\htdocs\website\resources\views\profiles.blade.php)
Here is the whole PagesController controller:
class PagesController extends Controller
{
public function home() {
return view('welcome');
}
public function about() {
$title = 'This is the about page';
return view('about')->with('title',$title);
}
public function show() {
$yomads = person::all();
return view('show')->with('yomads',$yomads);
}
public function profiles(){
return view('profiles');
}
public function check(Request $request){
$this->validate($request, [
'country' => 'required',
'age' => 'required',
'marks' => 'required',
'description' => 'required'
]);
return 123;
}
}
The error most likely has to do with the route (or lack of it) in app/Http/routes.php - check that it is properly defined there.
Furthermore, it is good practice to create custom request classes. Have a look at Form Request Validation
These can be generated with artisan:
php artisan make:request Profile
Then use it, as you were using the standard request:
public function check(ProfileRequest $request) {
[...]

Laravel 5.2 - not show errors

It's impossible to show errors in views
here is my Controller:
public function create(){
return view('articles.create');
}
public function store(Request $request){
$this->validate($request, [
'title' => 'required|max:5',
'content' => 'required',
]);
}
this is my view create.blade.php:
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops!</strong> Something went wrong!.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Kernel.php
ShareErrorsFromSession already there
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
here is the route.php
i have added the route in web
Route::group(['middleware' => ['web']], function () {
Route::get('articles/create', 'ArticlesController#create'); // Display a form to create an article...
});
Route::get('articles', 'ArticlesController#index'); // Display all articles...
Route::post('articles', 'ArticlesController#store'); // Store a new article...
Route::get('articles/{id}', 'ArticlesController#show');
You can try something like this.
$data = array();
$messages=array(
'required' => "You can't leave this empty",
);
$datavalidate = array(
'name' => $request->name,
);
$rules = array(
'name' => 'required',
);
$validator = Validator::make($datavalidate,$rules,$messages);
if($validator->fails()){
return Redirect::back()->withErrors($validator);
}
And now print it on the view file.
{!! dd($errors) !!}

Resources