AMIR HOSSEIN SOROURI AMIR HOSSEIN SOROURI - 5 months ago 68
PHP Question

Call to undefined method Illuminate\Database\Query\Builder::save() Error how to fix?

public function AddArtWork(Request $request){
$art = new Artwork;
$art->name = $request->name;
$art->date = $request->date;

if (!is_null($request->paintStyle)) {
# code...
$paint = new Paint;
$paint->style = $request->paintStyle;
$art->paint()->save($paint);
}
else if (!is_null($request->calligStyle)) {
# code...
$callig = new Calligraphy;
$callig->style = $request->calligStyle;
$art->calligraphie()->save($callig);
}
else if (!is_null($requst->substance)) {
# code...
$sclup = new Sculpture;
$sculp->substance = $request->substance;
$art->sculpture()->save($sculp);
}

if (!is_null($request->recievedDate)) {
# code...
$loan = new Loan;
$loan->date = $request->loanDate;
$art->loan()->save($loan);
}

else if (!is_null($request->storeOrexpose)) {
# code...
$perm = new Permanent_collection;
$perm->ExposeOrStore = $request->storeOrexpose;
$art->permanent()->save($perm);
}

$art->save();
return redirect('addartwork');
}


This is the function in my controller and when i use it it triggers the following error and i dont know what is wrong in my code.

Call to undefined method Illuminate\Database\Query\Builder::save()


my page view is:
enter image description here

i am trying to save request in the function but it doesn't work.
if you know how to fix this plz explain it.

Answer

This occurs cause your ArtWork object doesn't exist in database , you didn't save them. And when you try set relation on your object Laravel try to find his id and fail to do this.
Before saving relations for model you should save the model itself.

This should work

public function AddArtWork(Request $request){
    $art = new Artwork;
    $art->name = $request->name;
    $art->date = $request->date;   
    $art->save();     

    if (!is_null($request->paintStyle)) {
        # code...
        $paint = new Paint;
        $paint->style = $request->paintStyle;
        $art->paint()->save($paint);
    }
    else if (!is_null($request->calligStyle)) {
        # code...
        $callig = new Calligraphy;
        $callig->style = $request->calligStyle;
        $art->calligraphie()->save($callig);
    }
    else if (!is_null($requst->substance)) {
        # code...
        $sclup = new Sculpture;
        $sculp->substance = $request->substance;
        $art->sculpture()->save($sculp);
    }

    if (!is_null($request->recievedDate)) {
        # code...
        $loan = new Loan;
        $loan->date = $request->loanDate;
        $art->loan()->save($loan);
    }

    else if (!is_null($request->storeOrexpose)) {
        # code...
        $perm = new Permanent_collection;
        $perm->ExposeOrStore = $request->storeOrexpose;
        $art->permanent()->save($perm);
    }

    return redirect('addartwork');
}
Comments