Search code examples
phpmysqllaravelmass-assignment

passing an variable from controller to model with Mass Assignment in Laravel


I am new in Laravel.

I am going to upload image in Laravel I use Intervention Image and this is my 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();
        if(Image::make($image_temp->getRealPath())->save('public/up/city/'.$name)){
            $image='public/up/city/'.$name;
        }
        City::create($data);
        return Redirect::route('siteadmin.cities.index');
    }

And this is my model:

class City extends \Eloquent {
   protected $primaryKey='city_id';
   protected $fillable = ['name', 'parent_id', 'english_name','population','phone_prefix','image'];
}

And this is my route:

Route::resource('cities', 'CitiesController');

everything is working well but I don't know how to send an variable as a special field to Mass Assignment.

I need $image variable to save in cities table image field

if(Image::make($image_temp->getRealPath())->save('public/up/city/'.$name)){
                $image='public/up/city/'.$name;
            }

But image in my database filled with temporary name of uploaded file: enter image description here


Solution

  • Just override the value in the $data array:

    $data['image'] = 'public/up/city/'.$name;
    

    If you do

    $image = 'public/up/city/'.$name;
    

    ... you store the value in a local variable but nothing happens with it. The value in your DB comes from the "original" $data, the form data. It's the temporary path of the uploaded file. You need to change that in order for Laravel to fill the new value in the DB.


    And here the (nearly) full code to avoid any confusion:

    $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();
    if(Image::make($image_temp->getRealPath())->save('public/up/city/'.$name)){
        $data['image'] = 'public/up/city/'.$name;
    }
    City::create($data);
    return Redirect::route('siteadmin.cities.index');