ihprince's avatar

How to upload picture when register?

Hi, I'm trying to upload an image in laravel default user registration. I'm using laravel ui package.

Here is create method in RegisterController

protected function create(array $data) {

        if (request()->hasFile('image')) {
      	  $image = request()->file('image')->getClientOriginalName();
        	request()->file('image')->storeAs('avatars', $image, 'public');
    }
    return User::create([
        'name'     => $data['name'],
        'email'    => $data['email'],
        'address'  => $data['address'],
        'image'    => $image ,
        'contact'  => $data['contact'],
        'password' => Hash::make($data['password']),
    ]);

I'm getting this error TypeError

Argument 1 passed to App\Http\Controllers\Auth\RegisterController::create() must be an instance of Illuminate\Http\Request, array given

What is the right way to upload an image when registering?

0 likes
11 replies
ihprince's avatar

I changed this protected to public function . Right now, I got this error "Undefined variable: image"

Tray2's avatar

Try initialising the variable before the if statement.

ihprince's avatar

@tray2 I declare variable above if statement as,

$image = ' ' ;

registration is success but the image is not stored into the database.

Tray2's avatar

Are you sure you are passing the image in the request?

What do you get when you do this?

dd(request()->file('image'));
automica's avatar
automica
Best Answer
Level 54

@ihprince also ensure you have

enctype="multipart/form-data"

in your form or you wont be able to pass images when you post.

ihprince's avatar

By doing this

dd(request()->file('image'));

I get nothing. But doing this ,

dd($data);

I get the image

"image" => "avatar.png"

Tray2's avatar

I suggest you do this

public function create(Request $request) {

        if ($request->hasFile('image')) {
      	  $image = $request->file('image')->getClientOriginalName();
        	$request->file('image')->storeAs('avatars', $image, 'public');
    }
    return User::create([
        'name'     => $request->name,
        'email'    => $request->email,
        'address'  => $request->address,
        'image'    => $image ,
        'contact'  => $request->contact,
        'password' => Hash::make($request->password),
    ]);

Please or to participate in this conversation.