Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Hiccups's avatar
Level 10

Best approaches for creating a new user by admin.

Hey everyone,

I'm currently working on a project where only admins are allowed to create new users. I'm looking for the best practices or methods to handle this process effectively and securely.

Would love you if share your recommendations for:

  • Ensuring data validation and security. (I have already set up user permissions. How do I make sure when a link is sent to the user to set their password remains safe and secure?)
  • A place to store logic in User model/controller or create a separate AdminActions controller?
  • Sending welcome emails or notifications. (I'm having the user create their own password. How do I set this up?)
  • Logging and auditing user creation action

(I'm using Vuejs bridged by Intertiajs).

Thanks in advance.

0 likes
5 replies
LaryAI's avatar
Level 58

Certainly! Here’s a comprehensive solution to your question about creating new users by an admin, ensuring best practices for validation, security, and other aspects.

1. Ensuring Data Validation and Security

First, ensure that you validate the incoming data properly. Use Laravel's built-in validation to handle this. Additionally, make sure to sanitize the input to prevent any security vulnerabilities.

// In your AdminActionsController or UserController
public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        // other fields...
    ]);

    // Create the user
    $user = User::create([
        'name' => $validatedData['name'],
        'email' => $validatedData['email'],
        'password' => Hash::make(Str::random(8)), // Temporary password
    ]);

    // Send welcome email
    Mail::to($user->email)->send(new WelcomeEmail($user));

    // Log the action
    Log::info('User created by admin', ['admin_id' => auth()->id(), 'user_id' => $user->id]);

    return response()->json(['message' => 'User created successfully'], 201);
}

2. Storing Logic in User Model/Controller or Separate AdminActions Controller

For better separation of concerns, it’s a good idea to create a separate AdminActionsController to handle admin-specific actions. This keeps your UserController clean and focused on user-related actions.

// routes/web.php
Route::middleware(['auth', 'can:admin'])->group(function () {
    Route::post('/admin/users', [AdminActionsController::class, 'store']);
});

3. Sending Welcome Emails or Notifications

You can use Laravel's built-in mail functionality to send a welcome email. Create a Mailable class for the welcome email.

// app/Mail/WelcomeEmail.php
namespace App\Mail;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class WelcomeEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome')
                    ->with(['user' => $this->user]);
    }
}

4. Logging and Auditing User Creation Action

Use Laravel's logging functionality to log the creation of new users. This can be done in the same method where you create the user.

// In your AdminActionsController or UserController
use Illuminate\Support\Facades\Log;

public function store(Request $request)
{
    // Validation and user creation logic...

    // Log the action
    Log::info('User created by admin', ['admin_id' => auth()->id(), 'user_id' => $user->id]);

    return response()->json(['message' => 'User created successfully'], 201);
}

Vue.js and Inertia.js Integration

For the frontend part, you can create a form in Vue.js and handle the submission using Inertia.js.

<template>
  <div>
    <form @submit.prevent="createUser">
      <input v-model="form.name" type="text" placeholder="Name" required>
      <input v-model="form.email" type="email" placeholder="Email" required>
      <!-- other fields... -->
      <button type="submit">Create User</button>
    </form>
  </div>
</template>

<script>
import { Inertia } from '@inertiajs/inertia';

export default {
  data() {
    return {
      form: {
        name: '',
        email: '',
        // other fields...
      }
    };
  },
  methods: {
    createUser() {
      Inertia.post('/admin/users', this.form)
        .then(response => {
          // Handle success
        })
        .catch(error => {
          // Handle error
        });
    }
  }
};
</script>

Conclusion

By following these steps, you ensure that the process of creating new users by an admin is secure, well-structured, and maintainable. This approach also keeps your code organized and adheres to best practices.

1 like
martinbean's avatar

@az_shaheen What exactly is the problem? You just create a users controller in your admin panel, that only admins can access.

Hiccups's avatar
Level 10

@martinbean You literally dismissed the essence of my question and asked about a problem that doesn't exist. Thank you!

martinbean's avatar
Level 80

@az_shaheen I didn’t ask about a “problem that doesn’t exist”. At all. I’m trying to understand what the problem is.

Would love you if share your recommendations for:

  • Ensuring data validation and security. (I have already set up user permissions)

Only let logged-in admins create users via an admin panel.

  • A place to store logic in User model/controller or create a separate AdminActions controller?

You would have an Admin\UserController. Not an “AdminActions” controller. What would that controller even do? Are you just going to stuff every action for your admin panel in that controller? No. Create dedicated controllers for dedicated actions, just like you would outside of an admin panel.

  • Sending welcome emails or notifications. (I'm having the user create their own password.)

So send a welcome email when the user is created:

public function store(StoreUserRequest $request)
{
    $user = User::query()->create($request->validated());

    Mail::to($user, new WelcomeEmail());

    // Return response...
}
  • Logging and auditing user creation action

There are many Laravel packages to add auditing if that’s what you want.

All you need to do is break your requirements down one by one, and tackle them one by one. You’ve outlined how you want things to work, you just now need to write the code to make that happen.

1 like

Please or to participate in this conversation.