troubleshooting Question

How to insert a record into Laravel's User table...?

Avatar of Bruce Gust
Bruce GustFlag for United States of America asked on
LaravelPHP
7 Comments1 Solution183 ViewsLast Modified:
I want to be able to insert a user into the user table Laravel creates by default as a result of "php artisan auth." Basically, I'm adding a column to that table that gives my user administrative privileges.

I've got it done, for the most part, but there's one thing that keeps alluding me: I want to be able to create a "request" file where I can document some validation rules. When I do that, I get some errors and I'll elaborate on that in just a minute.

The one thing I've found recently is that when you look at the User model, you see this:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

From what I gather, "authenticatable" is going to invoke some validation rules by default. On top of that, when you look at the Controller that is made by the "auth" command, you see this:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

In other words, it seems like there's some validation built into this table by default and any attempt on my part to create a Request is going to step on some toes and probably generate some errors.

At least that's what I'm thinking.

When I run this code:

   public function store([b]CreateUserRequest[/b] $request)
    {
		$user = new User;
		if($request->input('admin_yes')=="Y") {
			$user->admin=1;
		}
		else {
			$user->admin=0;
		}
		$user->user_id = $request->input('user_id');
		$user->name=$request->input('name');
		$user->email=$request->input('email');
		$user->password = Hash::make($request->input('password'));
		$success='User was successfully created!';
		
		if($user->save()) {
			return View::make('/admin/displayUser')
			->with('user', $user)
			->with('newUser', 'Here\'s the user you just entered!')
			->with('adminPermissions', 'yes');
		}
    }

I get this error:

Method Illuminate\Validation\Validator::validateu{wud does not exist.

No idea where that's coming from or what it means.

But when I change the above code from this:

 public function store(CreateUserRequest $request)

to this:

 public function store(Request $request)

...no problem.

Granted, I may just go with the RegisterController.php page and stop trying to reinvent the wheel, but I want to understand what's going on under the hood.

Any ideas?
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros