laravellaravel-5.8domcrawler

Is there any issue in each loop to break it and not create models?


Is there any problem in following code, I tried so hard but got no answer. I want to create models in each iteration from loop in filtering dom.

$node->filter('div.panel-section.font-size-2.font-size-xxs-normal .row')->each(function (Crawler $nestedNode, $i) use (&$part) {
        $model_category = ModelCategory::firstOrCreate(['name' => $nestedNode->filter('.bold.mb-2 a')->first()->text()]);
        $part->modelCategories()->sync($model_category, false);
        $nestedNode->filter('.col-xs-6.col-md-3')->each(function (Crawler $columns, $i) use (&$model_category) {
             $model = Model::Create(['name' => $columns->filter('a')->first()->text()]);
             $model->category()->associate($model_category);
             $model->save();
        });
});

I have one to many relation between Model and ModelCategory


Solution

  • I found issue after sometimes looking and some searching. It's because of sync syntax. sync function in eloquent relationship get array of ids as first argument but I passed an object to it. Below is the corrected piece of code:

    $node->filter('div.panel-section.font-size-2.font-size-xxs-normal .row')->each(function (Crawler $nestedNode, $i) use (&$part) {
        $model_category = ModelCategory::firstOrCreate(['name' => $nestedNode->filter('.bold.mb-2 a')->first()->text()]);
        $part->modelCategories()->sync([$model_category->id], false);
        $nestedNode->filter('.col-xs-6.col-md-3')->each(function (Crawler $columns, $i) use (&$model_category) {
             $model = Model::Create(['name' => $columns->filter('a')->first()->text()]);
             $model->category()->associate($model_category);
             $model->save();
        });
    });