The part of form (the field text array)[1]:
<div id="cp1">
<div class="form-group">
{!! Form::text('names[]',null,['class'=>'form-control', 'maxlength'=>'30', 'placeholder'=>'Name']) !!}
</div>
<div class="form-group">
{!! Form::text('contents[]',null,['class'=>'form-control', 'maxlength'=>'30', 'placeholder'=>'Content']) !!}
</div>
</div>
When i send the form, validation fails with:
htmlentities() expects parameter 1 to be string, array given (View: /Applications/MAMP/htdocs/telovendogdl/resources/views/ads/new.blade.php)
this is the rules in form request:
return ['title' => 'required|min:8|max:100',
'description' => 'required|min:10|max:1100',
'price' => 'required|integer|max:15',
'city_name'=> 'required|max:70',
'category_id' => 'required|integer',
'delivery'=> 'max:70',
];
This is the function in the controller:[2]
public function newAdStore(StoreNewAdRequest $request)
{
$newAd = new Ad;
$newAd->user_id = \Auth::user()->id;
$newAd->active = 0;
$newAd->city_name = $request->input('city_name');
$newAd->category_id = $request->input('category_id');
$newAd->fill($request->all());
$newAd->save();
}
but only fails when i send the array fields from the form [1], when a delete this fields all works? what happen with that[2]?
I don't have a clear vision of your code but I am gonna try to help you debug your code ... first you need to add a rule to your StoreNewAdRequest to handle an array instead of string for names[] and contents[] :
public function rules()
{
$rules = [
'field2' => 'required|...',
'field3' => 'required|...',
....
];
foreach($this->request->get('names') as $key => $val)
{
$rules['names.'.$key] = 'required|max:100';
}
return $rules;
}
Make sure you have the right fillable params in your model
Note: the problem maybe occurred at this stage
$newAd->fill($request->all())
you are trying to fill an array of names[] & contents[] instead of strings ..
Related
for a dynamic form in which fields can be added and modified:
in form
<input name="gallery[1][title]">
<input name="gallery[1][text]">
.
.
.
<input name="gallery[n][title]">
<input name="gallery[n][text]">
in controller for validation:
'gallery.*.file' => 'nullable|image',
'gallery.*.title' => 'nullable|string',
in localization file:
I never know how many are going to be in the array.
'gallery.*.text' => 'text of gallery 1',
'gallery.*.title' => 'title of gallery 1',
how can I write it?
I want something like this in results:
title of gallery 1
.
.
.
title of gallery n
Here's a hacky way to do this. Unfortunately laravel does not currently support adding general message replacers for specific tokens so here's what you could do:
In controller:
$replacer = function ($message, $attribute) {
$index = array_get(explode(".",$attribute),1);
$message = str_replace(":index",$index,$message);
//You may need to do additional replacements here if there's more tokens
return $message;
}
$this->getValidationFactory()->replacer("nullable", $replacer);
$this->getValidationFactory()->replacer("string", $replacer);
$this->getValidationFactory()->replacer("image", $replacer);
$v = $this->getValidationFactory()->make($request->all(), $rules);
if ($v->fails()) {
$this->throwValidationException($request, $v); //Simulate the $this->validate() behaviour
}
You could also add the replacers in the service provider to have them available in all routes, but unfortunately you need to register them for each rule you want them available for.
In localisation file:
'gallery.*.text' => 'text of gallery :index',
'gallery.*.title' => 'title of gallery :index',
Update in laravel 7
your_language/validation.php
es it/validation.php
'attributes' => [
'gallery.*.file' => 'Your custom message!!',
],
Need to modify the form and controller validation
IN Form
{!! Form::open(['url' => 'actionURL']) !!}
{{ csrf_field() }}
<input name="gallery[]">
{!! Form::close() !!}
In Controller
foreach ($request->gallery as $key => $gallery) {
$validator = Validator::make(array('gallery => $gallery),
array('gallery' => 'required'));
}
I want to make an edit_Item functionality, but I'm having a little bit of trouble with routing when submiting the edited form. I get this error:
InvalidArgumentException in UrlGenerator.php line 314:
Route [userItems] not defined.
First of all, in my Edit page, I have a form which passes 2 arguments from the Items table (item_id and user_id) to the controller and it looks like this:
{!! Form::model($items, ['action' => ['ItemController#update', $items->id, $items->user_id], 'method' => 'PUT']) !!}
//Form inputs
{{ Form::close() }}
My Update controller looks like this:
public function update($id, $user_id){
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'title' => 'required',
'description' => 'required|description',
);
// store
$items = Item::find($id);
$items->title = Input::get('title');
$items->description = Input::get('description');
$items->save();
// redirect
Session::flash('message', 'Successfully updated item!');
return Redirect::route('userItems');
}
And my Route with the Update method looks like this:
Route::put('/userItems/{id}/{user_id}', 'ItemController#update');
Now, when I submit I'm currently getting routed to:
http://localhost:8000/userItems/26/3
And I need to get routed to:
http://localhost:8000/userItems/3
Any ideas on how to make the item_id(26) disappear from the route?
You could use an hidden input
Define a hidden field (not visible to a user).
Your form
{!! Form::model($items, ['action' => ['ItemController#update', $items->user_id], 'method' => 'PUT']) !!}
<input type="hidden" name="item_id" value="{{$items->id}}">
//Form inputs
{{ Form::close() }}
Your route
Route::put('/userItems/{user_id}', 'ItemController#update');
Your controller
public function update($user_id){
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'title' => 'required',
'description' => 'required|description',
);
// store
$item_id = Request::input('item_id');
$items = Item::find($item_id);
$items->title = Input::get('title');
$items->description = Input::get('description');
$items->save();
// redirect
Session::flash('message', 'Successfully updated item!');
return Redirect::route('userItems');
}
i am new to laravel.Here i have a form where i have to fill up a name field and send it to controllers store() method for validation. Otherwise it will show custom error.But whenever i submit the form with or without input i am getting the following error.
Argument 1 passed to Illuminate\Validation\Factory::make() must be of
the type array, string given, called in
C:\xampp\htdocs\mylaravel\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php
on line 221 and defined
for experiment purpose i am catching the user input using the following format
$data = $request->input('name');
create.blade.php:
<h1>login form</h1>
#if($errors->has())
<div><span> Opps !! </span></br>
<ul>
#foreach ($errors->all() as $error)
<li> {{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!!Form::open(array('url'=>'user','method'=>'POST', 'files'=>true)) !!}
{!!Form::label('name','Your name')!!}
{!!Form::text('name')!!}
</br>
{!!Form::submit('submit')!!}
{!!Form::close()!!}
store() method in userController.php file:
public function store(Request $request)
{
//
$data = $request->input('name');
$rules = array(
'name' => 'unique:users,name|required|alpha_num'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if($validator->fails()){
$errors=$validator->messages();
return Redirect::route('user.create')->withErrors($validator);
}else{
return Redirect::route('user.index');
}
}
}
According to your error,Validator expects it parameters to be array, but you are passing a string there as $data= $request->input('name') . So, you should pass array in Validator::make() . Below code should work for you.
$validator = Validator::make($request->all(), [
'name' => 'unique:users,name|required|alpha_num'
]);
Here is the doc if you want to explore more .
You need to pass array inside Validator::make.
Right now your are passing string in the form of $data variable.
For example :
$validator = Validator::make(
array('name' => 'Dayle'),
array('name' => 'required|min:5')
);
DOCS : https://laravel.com/docs/4.2/validation
you have pass your params as array in validation,so your code will be
public function store(Request $request)
{
//
$data = $request->all();
$rules = array(
'name' => 'unique:users,name|required|alpha_num'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if($validator->fails()){
$errors=$validator->messages();
return Redirect::route('user.create')->withErrors($validator);
}else{
return Redirect::route('user.index');
}
}
}
I have a validator, it has error messages, and my goal is to get only error messages with the field names.
$validator = Validator::make(
array(
'firstField' => Input::get('firstFieldName');
'secondField' => Input::get('secondFieldName');
),
array(
'firstField' => 'required';
'secondField' => 'required';
)
);
if($validator->fails()){
return $validator->messages();
}
So, this piece of code is returning some values to my js file as following
function getErrorMessages(){
//Some UI functions
var myDiv = document.getElementById('messageDivID');
$.post('validationRoute', function(returedValidatorMessageData)){
for(var a in returedValidatorMessageData){
myDiv.innerHTML = myDiv.value + a;
}
}
}
Problem is, the only values i get from post request is like firstField secondField but i'd like to get like firstField is required message. What would be the easiest way ?
Thanks in advance.
Laravel's messages() method returns array with this format:
[
"first_name" => [
"First name is required."
]
]
Where keys are name of the field and values are arrays of error messages. So just modify your js using values instead of keys. Example:
for (var key in returedValidatorMessageData){
console.log(returedValidatorMessageData[key]);
}
It's not a perfect approach i know, but created my own way as the answer :
if($validator->fails()){
//get all the messages
$errorArray = $validator->errors()->all(':message');
//& operator means changes will affect $errorArray
foreach($errorArray as &$a){
$a = ucfirst($a); //uppercases first letter (you can do this in laravel config too)
$a = '<li>'.$a.'</li>'; //add to list
}
//add a string at the beginning of error message
array_unshift($errorArray, '<p><b>The error messages are following :</b></p>');
//implode and return the value
return implode(' ',$errorArray);
}
You should search in laravel official documentation... in the view use this
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
in controller :
public function name(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
I've built a basic application in Laravel here - however I have two models namely an article and photo model. An Article can have many photos and so I have set up my form so that you can dynamically via javascript add multiple file inputs. The problem here is that if there are no validation errors the form works just swell - however if there is a validation error - I get this scary error message that says
htmlentities() expects parameter 1 to be string, array given (View: D:\wamp\www\one1\one1info-revamped\app\views\administration\articles\create.blade.php)
Here is the code of my store method in the controller:
public function store()
{
$input = Input::except('photos', 'captions');
$validation = Validator::make($input, Article::$rules);
$photos = Input::file('photos');
$captions = Input::file('captions');
if ($validation->passes() ){
$article = $this->article->create($input);
foreach($photos as $ii => $one_photo){
$photo = new Photo();
$name = $article->title . '-' . $ii;
$photo->create_n_upload($one_photo, array( 'name'=>$name,
'caption'=>$captions[$ii],
'imageable_type'=>'Article',
'imageable_id'=>$article->id ));
}
return Redirect::route('admin.articles.index');
}
return Redirect::route('admin.articles.create')
->withInput()->withErrors($validation);
}
I don't really know where am I getting this wrong here - also here is my article model:
class Article extends Eloquent {
protected $guarded = array();
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
public static $rules = array(
'title' => 'required',
'author' => 'required',
'caption' => 'required',
'body' => 'required',
'section_id'=>'required',
'dated'=>'',
'is_published' => 'required',
'created_by' => ''
);
}
You can see I haven't put any rules yet for the images - however just including them within the form has started to cause this error. It only happens if the validation fails - if everything is entered as required - it goes smoothly however I need to make sure that error handling is working fine here.
Here is what the upload file looks like on my form:
<li>
{{ Form::label('images', 'Images:') }}
ADD IMAGE
<div class="clearfix"></div>
<ul id="image-upload-holder">
<li>
<div class="well">
<input name="photos[]" type="file" />
{{ Form::text('captions[]') }}
<i class="icon-cross"/>
</div>
</li>
</ul>
</li>