I want to create a Category, if they have a parent categoryId
then update the parent id, and categoryName
on the subcategory Table
. if they have not parent id then, it saves on the parent Category table
with category name. Can you Correct my Relationship Code? I think it is wrong. and Very Thank you to Help me
in category Model (parent)
class Category extends Model
{
public function subcategories(){
return $this->hasMany(Subcategory::class);
}
}
In the Subcategory Model,
class Subcategory extends Model
{
public function category(){
return $this->belongsTo(Category::class);
}
}
In controller,
public function store(Request $request){
//dd($request->categoryid);
if($request->categoryid){
$subcategory = new Subcategory();
$subcategory->name = $request->subcatname;
$subcategory->save();
$category = $request->categoryid;
//dd($category);
$subcategory->category()->attach($category);
}
$category = new Category();
$category->name = $request->catname;
$category->save();
}
in dd($request)
+request: Symfony\Component\HttpFoundation\ParameterBag {#44 ▼
#parameters: array:3 [▼
"_token" => "z8kJy323B1Af27dKfHRHRHW1ON9NKHuP8DmYW06e"
"subcatname" => "Samsung"
"categoryid" => "1"
]
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire