Reputation: 1130
In my project, I'm working with polymorphic relations which I find very hard to understand. Do have in mind that I am a beginner in programming. My Database looks something like this:
Themes
id - integer
composer_package - string
name - string
Plugins
id - integer
composer_package - string
name - string
Products
id - integer
name - string
...
productable_id - integer
productable_type - string
In the store method below. I am getting the ID of the selected theme. Then I find that theme by doing $theme = Product::find($selectedTheme);
. The $selectedTheme is the ID of the theme. I have an Array which is called predefinedArray
which contains all the fillable fields of theme
. Then It puts all the values that that specific theme has in a session called chosen_theme.
public function store(Request $request)
{
$selectedTheme = null;
foreach($request->input('theme') as $key => $value) {
if($value === 'selected') {
$selectedTheme = $key;
}
}
$theme = Product::find($selectedTheme);
foreach($this->predefinedArray as $value) {
$request->session()->put('chosen_theme.' . $value, $theme->$value);
}
$data = $request->session()->all();
return redirect('plugins');
}
The theme is a product. I need to get the composer_package that is associated with it and put it in the request. Say, for instance, I find a theme with the ID 20, This theme's productable_id is 5. Then I need to get the composer_package in the Themes table where the ID is 5 and put it inside the request. How can I achieve that? The array currently looks like this:
As you can see, The composer_package field is empty, This needs to be filled with the composer_package that is associated with the selected product.
My models look like this:
Product
public function productable()
{
return $this->morphTo();
}
public function order_items()
{
return $this->hasMany(Orderitems::class);
}
Theme
public function webshops()
{
return $this->hasMany(Webshop::class);
}
public function products()
{
return $this->morphMany(Product::class, 'productable');
}
How can I achieve this? Thanks in advance!
Upvotes: 1
Views: 349
Reputation: 1908
When you are doing this
$theme = Product::find($selectedTheme);
You are loading the data from the product
table. The composer_package
field is however not stored in the product
table, but in the morphed row from the theme
/ plugin
table.
To access that value you need to do $theme->productable->composer_package
A quick and dirty way of doing that might be this:
foreach($this->predefinedArray as $value) {
$request->session()->put('chosen_theme.' . $value, $theme->$value);
}
$request->session()->put('chosen_theme.composer_package', $theme->productable->composer_package);
Upvotes: 2