Laravel FirstorNew()/FirstorCreate() Error in relationship

979 views Asked by At

i have 2 table called product and color products belongsTomany Colors and Colors belongsToMany Product using many to many relationship now i am trying to add more color in single product and checking color name first if its not there than create new here is my code

public function addproductdetailspost(Request $request, $product){
    $color_name = $request->color;
    $product = product::where('slug', $product)->firstorfail();
    $color = color::where('name', $color_name)->firstOrNew();
    $color->name = $color_name;
    $color->save();
    $product_id = $product->id;
    dd($product_id);
    $color_id = $color->id;
    $color->products()->attach($product_id);
    return Redirect::back()->with('status', 'Post Success');
}

but now i am getting error this

Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::firstOrNew()

Thank you

2

There are 2 answers

0
Ramy Herrira On BEST ANSWER

You don't need to use the where method for the Color model since firstOrNew does is it for you.

$color = color::firstOrNew(['name', $color_name]);
//$color->name = $color_name; No need s
$color->save();

Laravel 5.4 Documentation

0
Sid Heart On

i forgot to add arguments

$color = color::where('name', $color_name)->firstOrCreate(['name' => $color_name]);

now its working