0

in the store function in my controller I have:

public function store()
    {
        $validator = Validator::make($data = Input::all(), Item::$rules);

        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();
        }

        Item::create($data);

        return Redirect::route('spesas.index');
    }

What is missing is the user_id field.

I tought since the inserting user is the auth one, to not pass the id via POST, but retrieve it with Auth::user() in the controller (It seemed more secure).

Now I have the problem to insert the Auth::user() id in the input fields before Item::create($data);

Am I doing the Right Thing? Any suggestions?

Thanks,

1
  • Well, I don't know much about Laravel. But what speaks against $data['user_id'] = Auth::id(); before creating the item? Commented Aug 17, 2014 at 22:25

4 Answers 4

2

Just add your user id to the $data array by doing:

$data['user_id'] = Auth::user()->id;

Simple as that. :-)

Alternatively, you could have a hidden input field named 'user_id' and add the currently authorised users id as the fields value. Up to you.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll try the first solution. The hidden field opens a whole lot of other problems, since a malicious user can modify it and associate Items to other users.
True, though you could perform a check to see if the id passed corresponded to Auth::user()->id and if it didn't return back with the appropriate response.
1

The good old + sign will help you here:

Item::create($data + ['user_id' => Auth::id()]);

2 Comments

Nope :/ Still gave me SQLSTATE[23000]: Integrity constraint violation: 19 Item.user_id may not be NULL (SQL: insert into "items" ("amount", "context_id", "updated_at", "created_at") values (2, 2, 2014-08-18 07:11:41, 2014-08-18 07:11:41))
Uhm actually seems that Auth::id() is empty :_| (and I am sure I'm authenticated)
0

Try Auth::user()->id, not Auth::id()

Or

$item = new Item($data);
Auth::user()->items()->save($item);

1 Comment

Why not to use Auth::id() ?
0

So basically the cleaner solution I found is to inject, in the constructor of the model, the correct id. So I'll free the controller of the hassle ( and avoid duplicated code)

1 Comment

Please write down your code snippet so that people can know what you had used actually.

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.