mercredi 5 juin 2019

laravel Collection::saveMany does not exist

I have create function for save my one to many model, Model save success but when child saveMany, I don't know why show Error Message "Method Illuminate\Database\Eloquent\Collection::saveMany does not exist."

relate code

Model

class CarType extends Model {
public function cars() {
    return $this->hasMany(Car::class);
}
}
class Car extends Model {
public function type() {
    return $this->belongsTo(CarType::class);
}
}

Controller

public function store(Request $request, FormBuilder $formBuilder) {
    $form = $formBuilder->create($this->_formModel);
    // Valid
    if (!$form->isValid()) {
        return redirect()->back()->withErrors($form->getErrors())->withInput();
    }
    //get form input
    $inputs = FromMethod::getFormValue($form);

    $model = new CarType();

    //process
    $insert = (new MstProcess)->insertModel($model, $inputs , Car::class , 'cars');
    if(!$insert){
        return redirect()->route( 'admin.systemError');
    }
}

MstProcess

public function insertModel($model, $inputs ,$childClass = '' ,$childFiled = '') {
    DB::beginTransaction();
    try {
        $model->fill($inputs);
        $model->save();
        if($childClass != '' && array_key_exists($childFiled , $inputs ) ){
            $childs = $this->insertModelChild($childClass , $inputs[$childFiled]);
            $model->$childFiled->saveMany($childs);
        }

        DB::commit();
        return true;
    } catch (\Exception $e) {
        Log::debug('insertModel ' . $e);
        DB::rollback();
        return false;
    }
}

public function insertModelChild($childClass, $childsInputs) {
    $childs = [];
    foreach ($childsInputs as $i => $ary_childInputs) {
        $childModel = new $childClass();
        $childModel->fill(ary_childInputs);
        $childs[] = $childModel;
    }
    return $childs;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire