Search code examples
phpformsvalidationlaravelmass-assignment

Laravel Validation not returning error


I am new in Laravel.

This is my laravel controller:

public function store()
    {
        $validator = Validator::make($data = Input::all(), City::$rules);
        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();

        }
        $image_temp=Input::file('image');
        $name = Input::file('image')->getClientOriginalName();
        $data['image']='';
        if(Image::make($image_temp->getRealPath())->save('public/up/city/'.$name)){
            $data['image']='up/city/'.$name;
        }
        City::create($data);
        return Redirect::route('admin.cities.index');
    }

and This is my model:

class City extends \Eloquent {
   protected $primaryKey='city_id';

    // Add your validation rules here
    public static $rules = [
         'title'     => 'required',
         'image'     => 'mimes:jpeg',
         'parent_id' => 'required',
         'name'      => 'required',
         'english_name'=>'unique:cities,english_name|required'

    ];
    // Don't forget to fill this array
    protected $fillable = ['name', 'parent_id', 'english_name','population','phone_prefix','image'];
}

And I have a form I use {{ $errors->first('inputName','<p class="error">:message</p>') }} bellow my form inputs, when I send form without filling inputs I get error under each form input. But when I fill out all form inputs and then submit the Laarvel validation return fail (I mean mass assignment not working and not registering, and redirects back to create page.) what is the problem?


Solution

  • Almost always the reason for a mass assignment error is a missing attribute in the $fillable array. In your case it is title.

    protected $fillable = ['title', 'name', 'parent_id', 'english_name','population','phone_prefix','image'];
                              ^
    

    Edit

    Apparently the problem was actually that the title in the $rules array, which should have been name...