Search code examples
laravelvalidationmodeleloquentlaravel-5.5

Update does not work in Laravel, If I use different textbox name than column name in database


My table country has two fields country_id and country_name.

the textbox is using name country

<input type="text" class="form-control" value="{{Session::get('name')}}" name="country" >

CountryCOntroller code is

public function update(Request $request, $id)
{
 $this->validate($request, [
 'country' => 'required|country_name',
  ]);
   $updateCountry = $request->all();

    //update  data
    country::find($id)->update($updateCountry);
    return redirect('/admin/country');
}

my model is

 class country extends Model
{
protected $table = 'country';
protected $fillable = ['country_name'];
public $timestamps = false;
protected $primaryKey = 'country_id';
}

Solution

  • you need to change the name in the input filed to country_name as it should match the column name so it should be like this,

    <input type="text" class="form-control" value="{{Session::get('name')}}" name="country_name" >

    If you don't want to change that then you should change you controller where you send the array in to the update method. so something like this,

    public function update(Request $request, $id)
    {
     $this->validate($request, [
     'country' => 'required',
      ]);
    
    
        //update  data
        country::find($id)->update([
    'country_name' => $request->country
    ]);
        return redirect('/admin/country');
    }