Home > Software engineering >  Get the id of the user who created the new user in Laravel
Get the id of the user who created the new user in Laravel

Time:12-04

I have a users table and a column supervised_by where I want the id of the user who created the new user. For example: get the id of the admin in supervised_by column of the user the admin creates. users table

//migration file

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('verified')->default(false);
            $table->timestamp('verified_at')->nullable();
            $table->string('password');
            $table->string('is_verified');
            $table->boolean('active')->nullable();
            $table->integer('supervised_by')->references('id')->on('users');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

usercontroller

  public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:180',
            'email' => 'required|email|unique:users',
            'password' => 'required|max:15|min:8',
            // 'role' => 'required'

        ]);
        if ($validator->fails()) {
            return response()->json([
                'validation_errors' => $validator->messages(),
            ]);
        }
        else
        {
            $user = User::create([
                'name' => $request->name,
                'email' =>  $request->email,
                'password' => $request->password,
                'verified' => false,
                'role' => $request->role
            ]);

            return response()->json([
                'status' => 200,
                'code' => 'register',
                'message' => 'Registered successfully! You\'ll be able to log in once you are approved.',
                'data' => null,
                'error' => null,
            ]);

        }
    }

CodePudding user response:

You can use auth()->user()->id to get who created the user.

$user = User::create([
            'name' => $request->name,
            'email' =>  $request->email,
            'password' => $request->password,
            'verified' => false,
            'role' => $request->role,
            'supervised_by' => auth()->user()->id,
        ]);

You can read the documentation about it from here

CodePudding user response:

(If i understood correctly), the admin who creates the new users is always logged in, so you can track the admin id with following line:

$admin_id = Auth::user()->id;

or,

$admin_id = Auth::id();

Also, dont forget to:

use Illuminate\Support\Facades\Auth;
  • Related