mardi 20 mars 2018

Laravel - Get value associated with product

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:

enter image description here

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!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2G7Hrad
via IFTTT

Aucun commentaire:

Enregistrer un commentaire