I have two tables (City and Area). The city has many areas. So I have successfully added and deleted the data. But I am facing multiple errors while editing and updating. I have just started learning Laravel. I used a resource controller but encountered a problem with declaring routes, so I tried the name route also.
This error I have encountered: Trying to get property 'id' of non-object
and indicates the form's route ID. which is $editArea->id
. Here is my code.
web.php route:
Route::resource('area','Admin\AreaController');
Route::get('area/edit/{id}','Admin\AreaController@edit')->name('area.edit');
Route::post('area/update/{id}','Admin\AreaController@update')->name('area.update');
edit button: <a href="{{route('area.edit', $row->id)}}">Edit</a>
AreaController:
public function edit(Area $area, $id)
{
$editArea= Area::find($id);
$cityno= City::orderBy('city_name', 'asc')->get();
return view('admin.editArea', compact('editArea','cityno'));
}
public function update(Request $request, Area $area, $id)
{
$editArea=Area::find($id);
$editArea->city_id=$request->city_id;
$editArea->area_name=$request->area_name;
$editArea->save();
}
edit form:
<form method="POST" action="{{route('area.update', $editArea->id)}}">
@csrf
@method('put')
<select name="city_id">
@foreach($cityno as $row)
<option value="{{$row->id}}" >{{ucwords($row->city_name)}}</option>
@endforeach
</select>
<input type="text" name="area_name" value="{{$editArea->area_name}}">
<button type="submit">Update Area</button>
</form>
Area model:
public function city(){
return $this->belongsTo(City::class,'city_id');}
city model:
public function area(){
return $this->hasMany(Area::class); }
As I'm a new learner, I'm stuck in these files to find my wrong code.