0

I'm setting up a Laravel app that has a system where a user is created in an admin panel and then the user is emailed a link to login to the site and set up their details etc.

So, I have a route to handle creation of the user which looks like this:

public function store(UsersRequest $request)
{
    $user = User::create($request->all());

    event(new UserWasCreated($user));

    return redirect('/users');
}

So as you can see, the user is created from the request object which hold their username, first name, last name, email address and password.

What I'm aiming to do is also randomly generate a hash that will also be inserted in to the database. Now I can do this in the controller but I want to keep my controllers as skinny as possible.

So my thoughts are that I'll need to create some sort of class that is responsible for setting up the user. What I'm not sure of is how to approach this and where to put that class. I'm thinking along the lines of creating a service provider to handle this and using that in the controller.

Does that sound like a sensible way to approach this or is their other (better?) options that I could explore?

Thanks!

1

1 Answer 1

1

The easiest way to do this would be to use the creating event which automatically fires during the creation of an Eloquent model.

You can either use the boot() method of an existing a service provider or create a new one, or place this in the boot method of the User model itself.

User::creating(function ($user) {
    // Or some other way of generating a random hash
    $user->hash = md5(uniqid(mt_rand(), true));
});

There are several other events which can be used, all of which are documented on the Eloquent manual page.

http://laravel.com/docs/5.1/eloquent#events

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

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.