Validation errors are not output and fields with previous Form data are not returned - validation

Laravel 5.2
view where the form of sending data ('blade'):
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error ) <li>{{ $error }}</li> #endforeach
</ul>
</div>
#endif
<form method="POST" action="{{ route('contact') }}"> <!-- <?//='/contact');?> Or <?//=route('contact');?> -->
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" name="email" value="{{ old('email') }}" placeholder="Enter E-mail">
</div>
<div class="form-group">
<label for="site">Site:</label>
<input type="text" class="form-control" id="site" name="site" value="{{ old('site') }}" placeholder="Enter Site">
</div>
<div class="form-group">
<label for="text_area">Text:</label>
<textarea class="form-control" id="text_area" name="text_area" rows="3" placeholder="Some text....."> {{ old('text_area') }} </textarea>
</div>
<div class="checkbox">
<label><input type="checkbox" name="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div> <!--/class="col-"-->
</div> <!--/class="row"-->
ContactController.php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ContactController extends Controller {
public function show( Request $request, $prm=false ){
$my_array = ['title1'=>'This variable `$title1` content', 'title2'=>'This variable `$title2` content', 'title3'=>'This variable `$title3` content']; //массив
$my_array2 = ['one'=>array('param1'=>'This variable `param1` content', 'param2'=>'This variable `param2` content', 'param3'=>'This variable `param3` content'),
'two'=>array('param4'=>'This variabl e `param4` content', 'param5'=>'This variable `param5` content', 'param6'=>'This variable `param6` content')
];
$my_array3 = array(
'title'=>'Contact',
'data'=>[ 'one'=>'list 1',
'two'=>'list 2',
'three'=>'list 3',
'four'=>'list 4',
'five'=>'list 5',
],
'dataI'=>['list-1','list-2','list-3','list-4','list-6','list-6'],
'bvar'=>true,
'script'=>"<script>alert('Hello! ++')</script>"
);
/** VALIDATION on Request */
if( $request->isMethod('post') ) {
$rules = [
'name' => 'required|max:10',
'email' => 'required|email',
//'site'=>'required',
//'text_area'=>'required',
];
$messages = [
'required' => 'The :attribute field is required.',
];
$this->validate($request, $rules, $messages);
dump( $request->all() );
dump( $request->session()->all() );
}
if( view()->exists('default.contact') ){
return view('default.contact')
->withMydata($my_array2)
->withMydata2($my_array)
->withMydata3($my_array3);
}
else { abort(404); }
}
}
/app/Http/Kernel.php
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
How can I see that validation fulfills and its rules are in effect,
But I do not see the display of validation errors when it is not passed and the data in the input fields when the Form is filled when redirecting back.

Let me show you my method which also uses validation on Laravel 5.2 and find out what the difference you have with this code:
The Controller which handles the request:
$validator = \Validator::make($request->all(), [
'data1' => 'required',
'data2' => 'required|in:bla1,bla2,bla3',
'data3' => 'required|array',
'data3.*' => 'required|json',
'data4' => 'required_if:data2,bla2',
]);
if ($validator->fails()) {
$request->flash();
return \Response::make(\View::make('theform')
->withErrors($validator)
->withInput($request->all())
->render()
, 406);
}
The form which contains the form which has been submitted and redrawn with error logs, named 'theform':
<input type="text" class="form-control" name="trip_name" id="trip_name"
placeholder="Gezi ismi" value="{{ old('trip_name') }}">
#if ($errors->has('trip_name'))
<span class="help-block">
<strong>{{ $errors->first('trip_name') }}</strong>
</span>
#endif
This is one way to show it. You can also view it your way as:
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error )
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Well, the problem did not stop there ))
I create the validation through my own class Request and divide routes for GET and POST and defined separate methods for them in my Controller.
1. app/Http/routes.php
Route::get('/contact_form/{prm?}', ['uses'=>'Admin\ContactformController#show_form_get'])->name('contact_form');
Route::post('/contact_form', ['uses'=>'Admin\ContactformController#show_form_post']);
2. app/Http/Requests/ContactRequest.php - my custom Request class with validation rules:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactRequest extends Request
{
public function authorize()
{
return true; //false
}
public function rules()
{
return [
'name' => 'required|max:10',
//'name' => 'exists:users,name',
'email' => 'required|email',
'site'=>'required',
];
}
} //__/class ContactRequest
3. app/Http/Requests/ContactRequest.php - my Controller with POST and GET handling:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\ContactRequest; //custom Request class with validation rules
use App\Http\Controllers\Controller;
use \Illuminate\Support\Facades\Validator;
class ContactformController extends Controller {
public $show_controller_method = array(__METHOD__);
/** Method handler http-request with GET
*/
public function show_form_get( ){
$this->show_controller_method[] = 'showform()';
if( view()->exists('default.contact_form') ){
return view('default.contact_form')->withInfoMethodController($this->show_controller_method);
}
else { abort(404); }
} //__/public function show_form_get()
/** Method handler http-request with POST
*/
public function show_form_post( ContactRequest $request ){
if( $request->isMethod('post') ):
dump( $request->all() );
endif;
}
3. The view remained the same and there is a return of data "old inputs":
value="{{ old('name') }}" value="{{ old('email') }}" and so on...
and errors of validation if they exist:
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error ) <li>{{ $error }}</li> #endforeach
</ul>
</div>
#endif
Now the validation works (if it passes successfully - I see a dump() the POST.
If the validation falls, then a redirect occurs, but there are no validation errors and there are no old inputs.
Tell me please what I'm doing is not right?

Related

How in laravel-livewire set flash message with validation erros

With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form

Edit two unique value with laravel

I have a problem with my Laravel 5.8 project. I want to edit one of two field that both have unique value.
Blade:
#extends('layouts.master')
#section('content')
<h1>CHANGE SURGICAL DIVISION</h1>
<a href="/surgical-div">
<button type="button" class="btn btn-primary btn-sm">BACK</button><br>
</a>
#if (session('mess'))
<div class="alert alert-success">
{{ session('mess')}}
</div>
#endif
<form method="POST" action="/surgical-div/{{ $surgicaldivs->id_surgical_div }}">
#method('patch')
#csrf
<div class="form-group">
<label for="name_surgical_div">Surgical Division Name: </label>
<input type="text" value="{{ $surgicaldivs->name_surgical_div }}"
class="form-control #error('name_surgical_div') is-invalid #enderror" id="name_surgical_div" name="name_surgical_div"
placeholder="Insert The Surgical Division">
#error('name_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group">
<label for="initial_surgical_div">Surgical Division Initial : </label>
<input type="text" value="{{ $surgicaldivs->initial_surgical_div }}"
class="form-control #error('initial_surgical_div') is-invalid #enderror" id="initial_surgical_div" name="initial_surgical_div"
placeholder="Insert Surgical Division Initial">
#error('initial_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-success btn-sm">Save</button>
</form>
#endsection
Controller:
public function edit($id)
{
$surgicaldivs = SurgicalDiv::withTrashed()->find($id);
return view('pages.surgical_div.surgical_div_edit', compact('surgicaldivs'));
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SurgicalDiv extends Model
{
//Table Name
protected $table = 'surgical_div';
// Primary Key
protected $primaryKey = 'id_surgical_div';
//Soft Deletes
use SoftDeletes;
//Fillable Field
protected $fillable = ['name_surgical_div', 'initial_surgical_div'];
}
This is the update in the controller that i've tried :
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div',
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div'
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
I don't know what to put on the update function in the controller. I want to update one or even both of the field from my blade.
Try this
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div,'.$id,
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div,'.$id
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
This will check the table for same entries except the row with the $id. This way you can check if there are any other rows with same values in the two columns.

Send email and get reply in laravel form

I'm succeed to send mail from contact form, and now my requirement is to get automated success reply to the users input email address when submitting the form. please help me on this
ContactUsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactUs;
class ContactUsController extends Controller
{
function index()
{
return view('home/contactus');
}
function send(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'message' => $request->message
);
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
return back()->with('success', 'Thanks for contacting us! We will get back to you soon.');
}
}
ContactUs
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactUs extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->from('xxxx#mail.com')
->subject('Customer Feedback')
->view('dynamic_email_template')
->with('data', $this->data);
}
}
Form
<div class="form">
<h4>Send us a message</h4>
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data- dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data- dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="{{url('contactus/send')}}" autocomplete="off">
{{ csrf_field() }}
<div class="form-group">
<input type="text" name="name" for="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" for="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" for="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" for="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center">
<button type="submit" name="send" title="Send Message">Send Message</button>
</div>
</form>
</div>
dynamic_email_template
<p>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</p> </br>
<p>{{ $data['subject'] }}</p> </br>
<p>I have some query like "{{ $data['message'] }}".</p> </br>
<p>It would be appriciative, if you gone through this feedback.</p>
You need to create email template same like your view file, lets say contact_us_email.blade.php. In this file add this content
contact_us_email.blade.php
<html>
<body>
<h2>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Subject: {{ $data['subject'] }}</p> <br>
<p>I have some query like <b>"{{ $data['message'] }}"</b>. <br>
<p>It would be appriciative, if you gone through this feedback.</p>
</body>
</html>
NOTE: Add css or styling according to your need. this is basic html
Edit: To send confirmation email to user
For success confirmation to user, you can create another email template like
contact_us_thank_you_email.blade.php
<html>
<body>
<h2>Hello, {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Thank You for your interest...blah blah blah</p> <br>
<p>Our team will contact you soon</p> <br>
</body>
</html>
Now in your ContactUsController, replace
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
with
Mail::send('contact_us_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to('xxx#mail.com')->subject($data['subject']);
});
Mail::send('contact_us_thank_you_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to($data['email'])->subject('Thank you for the interest');
});
And I think you are good to go with this. I hope this is what you are asking for.

Laravel - If has errors on validation, insert class in the specifics inputs

I'm totally noob in PHP, but my question is, after the validation which has errors for specific inputs, how can I insert a class in the specific input?
Example, if i have this error in the validation: "The email field is required."
How can i insert a specific class in the email input?
Login routes:
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'Admin\AdminController#index');
Route::get('login', 'Admin\AuthController#getLogin');
Route::post('login', 'Admin\AuthController#postLogin');
Route::get('logout', 'Admin\AuthController#getLogout');
});
AdminController:
class AdminController extends AdminBaseController
{
public function index()
{
if(Auth::user()){
return view('admin/pages/admin/index');
}
return view('admin/pages/login/index');
}
}
AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/admin';
public $loginPath = '/admin';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
public function getLogin()
{
if(Auth::user()){
return redirect('/admin');
}
return view('admin/pages/login/index');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
}
}
My blade form:
<form class="s-form" role="form" method="POST" action="/admin/login">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="s-form-item text">
<input type="text" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
<div class="s-form-item text">
<input type="password" name="password" value="{{ old('password') }}" placeholder="Senha">
</div>
<div class="s-form-item">
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
<input class="s-btn" type="submit" value="Entrar">
</div>
</form>
You can pass an argument to the has method to specify the specific key.
For example, for your email input...
<input class="#if($errors->has('email')) some-class #endif" ... >
I left out the rest of the input field for brevity. It basically checks if an error for the email input exists. If so, 'some-class' is outputted. Otherwise, it skips over it.
Edit: To answer the question on how you can customize where to output your error messages, you can use the get or first methods in conjunction with the has method. For example...
#if ($errors->has('email'))
#foreach ($errors->get('email') as $error)
<p>{{ $error }}</p>
#endforeach
#endif
The has method has already been explained. The get method retrieves the validation errors. Because there can be more than one validation error, you must loop through it and output it.
In the next example, I use first. This method just outputs the first error message so there is no need to loop through it.
#if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
#endif

How to use custom validation attributes on an array of inputs

I'm using Laravel to build a form that contains an array of inputs and I’m having difficulty in showing the translated attribute name when a validation error occurs. For simplicity sake I will post a simple example of my problem.
Form inside the view:
<form method="POST" action="{{ route('photo.store') }}" accept-charset="UTF-8" role="form">
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div class="row">
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfield') ? ' has-error' : '' }}">
<label class="control-label"
for="testfield">{{ trans('validation.attributes.testfield') }}</label>
<input class="form-control" name="testfield" type="text" id="testfield"
value="{{ old('testfield') }}">
#if ($errors->has('testfield'))
<p class="help-block">{{ $errors->first('testfield') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.0') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-0">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-0"
value="{{ old('testfieldarray.0') }}">
#if ($errors->has('testfieldarray.0'))
<p class="help-block">{{ $errors->first('testfieldarray.0') }}</p>
#endif
</div>
</div>
<div class="col-lg-12">
<div class="form-group{{ $errors->has('testfieldarray.1') ? ' has-error' : '' }}">
<label class="control-label"
for="testfieldarray-1">{{ trans('validation.attributes.testfieldarray') }}</label>
<input class="form-control" name="testfieldarray[]" type="text" id="testfieldarray-1"
value="{{ old('testfieldarray.1') }}">
#if ($errors->has('testfieldarray.1'))
<p class="help-block">{{ $errors->first('testfieldarray.1') }}</p>
#endif
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<input class="btn btn-primary" type="submit" value="Gravar">
</div>
</div>
Rules function in the form request:
public function rules() {
$rules = [
'testfield' => array('required'),
];
foreach ($this->request->get('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = array('required');
}
return $rules;
}
lang/en/validation.php
'attributes' => [
'testfield' => 'Test Field',
'testfieldarray' => 'Test Field Array',
],
The validation is performed correctly, as do the error messages. The only problem in the error messages is the name of the attribute displayed. In both array inputs, the attribute name inserted in the message is 'testfieldarray.0' and 'testfieldarray.1' instead of 'Test Field Array'. I already tried to add on the language file 'testfieldarray.0' => 'Test Field Array', 'testfieldarray.1' => 'Test Field Array', but the messages remain unchanged. Is there a way to pass the attribute names correctly?
Just see the example to add custom rules for integer type value check of array
Open the file
/resources/lang/en/validation.php
Then add the custom message.
// add it before "accepted" message.
'numericarray' => 'The :attribute must be numeric array value.',
Again Open another file to add custom validation rules.
/app/Providers/AppServiceProvider.php
So, add the custom validation code in the boot function.
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}
Now you can use the numericarray for integer type value check of array.
$this->validate($request, [
'input_filed_1' => 'required',
'input_filed_2' => 'numericarray'
]);
----------- Best of Luck --------------
1-if you split the validation in file request then add the method attributes and set the value of each key like this :
public function attributes()
{
return [
'name'=>'title',
];
}
2- but if don't split the validation of the request then you just need to make variable attributes and pass the value of items like this :
$rules = [
'account_number' => ['required','digits:10','max:10','unique:bank_details']
];
$messages = [];
$attributes = [
'account_number' => 'Mobile number',
];
$request->validate($rules,$messages,$attributes);
// OR
$validator = Validator::make($request->all(), $rules, $messages, $attributes);
Use custom error messages inside your parent method....
public function <metod>(Request $request) {
$rules = [
'testfield' => 'required'
];
$messages = [];
foreach ($request->input('testfieldarray') as $key => $val) {
$rules['testfieldarray.' . $key] = 'required';
$messages['testfieldarray.' . $key . '.required'] = 'Test field '.$key.' is required';
}
$validator = Validator::make($request->all(), $rules,$messages);
if ($validator->fails()) {
$request->flash();
return redirect()
->back()
->withInput()
->withErrors($validator);
}
}
}

Resources