1

I have a problem with create() method in Laravel. Every time when I try to create new record in database using this code:

    $website = Website::create([
        'user_id' => auth()->user()->id,
        'name' => $request->name,
        'url' => $request->url,
        'description' => $request->description,
        'subcategory_id' => $request->subcategory_id,
        'user_id' => $request->subcategory_extra_id,
    ]);

the column user_id (in database) equals to 0 whereas my id is 1. Of course I have fillable variable in my model:

    protected $fillable = [
    'user_id',
    'name',
    'url',
    'description',
    'subcategory_id',
];

I tried to use constant value instead of auth()->user()->id but I still have 0 as user_id in database. Using save() method solves this problem but I prefer to use create().

1
  • try dd(auth()->user()->id) or dd(auth()->id()) is it give you correct value? Commented Aug 3, 2017 at 16:47

3 Answers 3

0

You have listed user_id twice in your keys. The 2nd time, the integer is empty.

'user_id' => $request->subcategory_extra_id,
//observe
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't noticed that... Thank you!
0

Why you used 'user_id two times in your code? one is

'user_id' => auth()->user()->id, 

and another one is

'user_id' => $request->subcategory_extra_id,

Just use one instead of two. And try to use the follwing way:

'user_id' => Auth::user()->id;

Remember: in this case you have to use the namespace of Auth class.

Hope it will work

Comments

0

try to use this use Auth namespace and then

$website = Website::create([
        'user_id' => Auth::user()->id,
        'name' => $request->name,
        'url' => $request->url,
        'description' => $request->description,
        'subcategory_id' => $request->subcategory_id,
    ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.