Mar 7, 2017
0
Level 7
Laravel 5.1 Update data with relation
I want to update the model Chapters (table: Chapters).
Right now it does not update the table I get following error:
BadMethodCallException in Macroable.php line 81: Method product does not exist.
Here is a little scretch of the 2 database tables:
Chapters:
id | product_id | name
_________________________________________________
3 | 2 | jon doe
Products:
id | ...
_____________________________________
2 | ...
I want to update / add a chapter to my chapters table.
My update method:
public function updateProduct(Request $request)
{
...
$productID = $data['id'];
$product = Product::find($productID);
...
$chapters = $request->input('chapters', []);
if(count($chapters) > 0)
{
$chaptersData = array();
$o = 1;
$inputChapters = Chapters::where('product_id', $product->id)->get();
foreach ($chapters as $chapterKey => $chapterValue)
{
$inputChapters->chapter_name = $chapterValue['chapter_name'];
# .. some more
$chaptersData[] = $inputChapters;
$inputChapters->product()->associate($product);
$inputChapters->save();
$o++;
}
}
...
}
Edit my chapter model
<?php
class Chapters extends Model
{
protected $table = 'chapters';
protected $fillable = ['product_id', 'chapter_name'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
}
Please or to participate in this conversation.