Laravel 4 :: custom validation error message is not displaying? - validation

I'm trying to create an online form and to display my own error messages. But for some reason it's not working correctly. Here's my controller code, CategoryController.php:
class CategoryController extends BaseController
{
public function add()
{
return View::make('admin');
}
public function validate_add()
{
$rules = array('category_name' => 'Required|Alpha|Min:4');
$messages = array('category_name.Required' =>'Please enter the category name');
$input = Input::all();
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin')->withErrors($validator)->withInput(Input::all());
}
else
{
echo '<h1>WOW! your are are awesome!!! <3<h1> ';
}
}
}
And the admin.blade.php is following:
#extends('common')
#section('body')
<h1>Add Category</h1>
{{ HTML ::ul($errors->all(), array('class'=>'errors')) }}
{{ Form::open(array( 'url'=>'admin', $title="Admin Control Panel")) }}
<p>
{{ Form::label('Category Name:') }}
{{ Form::text('category_name', Input::old('category_name')) }}
</p>
<p>
{{Form::label('Parent Category') }}
{{ Form::select('Network', array('0' => 'Maincategory')) }}
</p>
<p>
{{ Form::submit('Submit') }}
</p>
{{ Form::close() }}
#stop

Interesting - I tried this on my local Laravel project and it looks like although you can specify your rules in mixed case, you need to specify the custom messages in lower case.
So if you changed your rules and your message override to; 'required' instead of 'Required' etc., it should work.

Related

How to pass array to flash message?

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?
if(!empty($additional_features)){
foreach($additional_features as $additional_feature){
$data = [
'name' => $additional_feature,
];
if (!Feature::where('name', '=', $additional_feature)->exists()) {
$additional = Feature::firstOrCreate($data);
$additional_ids[] = $additional->id;
}
else{
return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
}
}
}
You can use session() instead of with():
session->flash('someVar', $someArray);
Another thing you could try is to seriallize array and pass it as string. Then unserilize it and use.
Also, you could save an array using simple session:
session(['someVar' => $someArray]);
Then get it and delete manually:
session('somevar');
session()->forget('someVar');
We had the same problem and forked the package. you can find it here:
Forked at first from Laracasts/Flash to use multiple message
#if (Session::has('flash_notification.message'))
#if (Session::has('flash_notification.overlay'))
#include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
#else
<div class="alert alert-{{ Session::get('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! Session::get('flash_notification.message') !!}
</div>
#endif
#endif
And the content of the include flash::modal
#if (Session::has('flash_notification.messages'))
#foreach (Session::get('flash_notification.messages') as $flashMessage)
#foreach($flashMessage as $type => $message)
<script>
$(function() {
var message = ('{{ $message }}<br>').replace(/'/g, "’");
customFlashMessage({
type: "{{ $type }}",
message: message
});
});
</script>
#endforeach
#endforeach
#endif
return redirect()->back()->with(['session1' => $value, 'session2' => $value]);
In the blade template:
{{ Session::get('session1') }}
{{ Session::get('session2') }}

serialization of 'closure not allowed' Error

Below is the code from my product view:
{{ Form::open(array('url'=>'admin/products/create' , 'files'=>true)) }}
<p>
{{ Form::label('category_id' , 'Category') }}
{{ Form::select('category_id' , $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form::text('title') }}
</p>
<p>
{{ Form::label('description') }}
{{ Form::textarea('description') }}
</p>
<p>
{{ Form::label('height') }}
{{ Form::text('height' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('width') }}
{{ Form::text('width' , null , array('class'=>'form-price')) }}
<!--{{ Form::label('image' , 'Choose an image') }}
{{ Form::file('image') }}-->
</p>
<p>
{{ Form::label('length') }}
{{ Form::text('length' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('color') }}
{{ Form::text('color' , null , array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('material') }}
{{ Form::text('material' , null , array('class'=>'form-price')) }}
</p>
{{ Form::submit('Create Product' , array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
and below is the code from my product controller:
<?php
/**
*
*/
class ProductsController extends BaseController {
public function __construct() {
$this->beforeFilter('csrf' , array('on'=>'post'));
}
public function getIndex() {
/* NOTE :: the categories array is being
created so that the products index page
can have access to all the availability
categories */
$categories = array();
foreach (Category::all() as $category) {
$categories[$category->id] = $category->name;
}
return View::make('products.index')
->with('products' , Product::all())
->with('categories' , $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all() , Product::$rules);
if($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->height = Input::get('height');
$product->width = Input::get('width');
$product->length = Input::get('length');
$product->color = Input::get('color');
$product->material = Input::get('material');
/* code for saving the image */
/* $image = Input::file('image');
$filename = date('Y-m-d-H-i-s')."-".$image->getClientOriginalName();
$path = public_path('img/products/' .$filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename; */
/*end of code for saving the image */
$product->save();
return Redirect::to('admin/products/index')
->with('message' , 'Product created');
}
return Redirect::to('admin/products/index')
->with('message' , 'something went wrong')
->withError($validator)
->withInput();
}
public function postDestroy() {
$product = Product::find(Input::get('id'));
if ($product) {
$product->delete();
return Redirect::to('admin/products/index')
->with('message' , 'product has been deleted');
}
return Redirect::to('admin/products/index')
->with('message' , 'something went wrong , Please try again');
}
}
?>
Now when i fill the values in the form and click on submit i get a error as follows :
Error image
serialization of 'closure not allowed' , on googling a bit i found the following helpful thread:
Related thread,
the accepted solution is not applicable to me and i tried the solution in the second answer and i still have the same error.
I still don't understand what could be the cause of this error or what am i doing wrong ? can anybody explain ?
Unless it is a typo in the code you have posted, the accepted solution to the related question you posted does relate to you.
On your return statement, you have ->withError($validator), this should be ->withErrors($validator) (you're missing the 's').

Laravel 4 - no guessers available issue

I get this error: LogicException: Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?) while trying to upload an image.
I have enabled the php_fileinfo extension and also restarted the Wamp web server but I still unable to solve this. What am I missing? Thanks
Below are my codes:
Models: Product.php
class Product extends Eloquent {
protected $fillable = array('category_id', 'title', 'description', 'price', 'availability', 'image');
public static $rules = array(
'category_id'=>'required|integer',
'title'=>'required|min:2',
'description'=>'required|min:20',
'price'=>'required|numeric',
'availability'=>'integer',
'image'=>'required|image|mimes:jpeg,jpg,bmp,png,gif|max:3000',
);
public function category() {
return $this->belongsTo('Category');
}
}
Controllers: ProductsController.php
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468,249)->save('public/img/products/'.$filename);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->WithInput();
}
Views: Index.blade.php
{{ Form::open(array('url'=>'admin/products/create', 'files'=>true)) }}
<p>
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form::text('title') }}
</p>
<p>
{{ Form::label('description') }}
{{ Form::textarea('description') }}
</p>
<p>
{{ Form::label('price') }}
{{ Form::text('price', null, array('class'=>'form-price')) }}
</p>
<p>
{{ Form::label('image', 'Choose an image') }}
{{ Form::file('image') }}
</p>
{{ Form::submit('Create Product', array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
uncomment this line in php.ini into php folder.
extension=php_fileinfo.dll
and restart the server(enter 'php artisan serve' again). This way will works!
Open php.ini file and you can find ;extension=php_fileinfo.dll remove the semi-coloumn to extension=php_fileinfo.dll will work perfectly then restart the your apache server or xampp ,wampp whatever environment you are using
I think is the WAMP Web Server's Bug. I switched to XAMPP Web Server and it works fine.
Thanks alot by the way.

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources