Create workspace for a user after signing up in laravel

79 Views Asked by At

I want to Create workspace for each user after signing up

Do you have any suggest for how to do it?

Should i code it in Controller, Event or Observer? which one is clean code?

RegisterController

    $data = $request->all();
    $data['password'] = bcrypt($data['password']);

    $user = User::create($data);

    $user->workspaces()->create([
        'name' => $data['workspace_name']
    ]);
1

There are 1 best solutions below

0
Henning On

there is no "right" answer. I tend to implement a UserService class because

  • The Controller should only handle requests and responses
  • The Model should only hold and handle the data
  • Events and Observers should only trigger such things but not implement it

Example:

namepsace App\Services;

use \App\Models\User;

class UserService
{
    public function createUser(array $data): User
    {
        $user = User::create($data);
        $user->workspaces()->create([
            'name' => $data['workspace_name']
        ]);
        return $user;
    }
    
    [..]
}

Now you can inject this service in the Controller:

use \App\Services\UserService;

[..]

class UserController extends Controller
{
    public function store(Request $request, UserService $userService)
    {
        $data['password'] = bcrypt($data['password']);
        $user = $userService->createUser($request->all());
        return $user;
    }

    [..]
}

As said it is only one of many ways but I like it because it feels quite "laravely".