首页 > 解决方案 > 如何在用户注册时通过 Auth/RegisterController 存储头像(图像文件)?

问题描述

我的意图是存储带有用户注册的个人资料图片。我正在使用 Laravel 6 用户身份验证。我试着用给定的方法来做。

我的html代码是这样的..

<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
    @csrf
    <input type="text" name="name" placeholder="Name"><br>
        @error('name')
            <div>{{$message}}</div>
        @enderror
    <input type="file" name="avatar" placeholder="Profile photo"><br>
        @error('avatar')
            <div>{{$message}}</div><br>
    @enderror
</form>

我在 Auth/RegisterController.validator() 中添加了验证。我添加了字段来存储数据以创建函数。RegisterController 类如下..

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
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 = RouteServiceProvider::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'],
            'avatar' => ['mimes:jpeg,jpg,png,gif','required','max:10000']
        ]);
    }
    /**
     * 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'],
            'avatar' => file($data['avatar'])->store('avatars')
        ]);
    }
}

当我尝试运行此代码时,将发生此错误

Error
Call to a member function store() on array
http://localhost:8000/register 

注意:我删除了电子邮件、密码和其他字段只是为了减少行数..

标签: phplaravellaravel-6

解决方案


您可以通过以下步骤上传具有 laravel 默认注册的头像。

1)在您的迁移中添加头像字段

$table->string('avatar');

2)在用户模型中添加avatar字段$filable

protected $fillable = [
    'name', 'email', 'password', 'avatar',
];

3)在中添加头像输入字段register.blade.php

<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar') }}</label>

    <div class="col-md-6">
        <input id="avatar" type="file" class="form-control @error('avatar') is-invalid @enderror" name="avatar" value="{{ old('avatar') }}" required autocomplete="avatar" autofocus>

        @error('avatar')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

4)在函数中添加头像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:6', 'confirmed'],
        'avatar' => ['required', 'image'],
    ]);
}

create5)函数中处理文件上传

protected function create(array $data)
{
    $request = app('request');
    if ($request->hasfile('avatar')) {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();

        //Implement check here to create directory if not exist already 

        Image::make($avatar)->resize(300, 300)->save(public_path('uploads/avatars/' . $filename));
    }

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'avatar' => !empty($filename) ? $filename : 'default_avatar.png',
    ]);
}

6)在尝试运行此之前,请确保您的控制器中有可用的图像类,如果您没有图像类,您可以通过执行以下步骤将其包含在您的项目中。

composer require intervention/image

现在打开 config/app.php 文件。将此添加到 $providers 数组。

Intervention\Image\ImageServiceProvider::class

接下来将其添加到 $aliases 数组中。

'Image' => Intervention\Image\Facades\Image::class

现在像这样在用户控制器中包含图像类

use Image;

尝试运行您的项目,它应该可以正常工作。


推荐阅读