Sid Heart
Sid Heart

Reputation: 743

Laravel FirstorNew()/FirstorCreate() Error in relationship

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

Upvotes: 0

Views: 1003

Answers (2)

Ramy Herrira
Ramy Herrira

Reputation: 624

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

Upvotes: 3

Sid Heart
Sid Heart

Reputation: 743

i forgot to add arguments

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

now its working

Upvotes: 0

Related Questions