首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >注册时不加载laravel9图片

注册时不加载laravel9图片
EN

Stack Overflow用户
提问于 2022-08-25 15:45:52
回答 1查看 36关注 0票数 0

我尝试添加这样的内容,以便用户在注册时必须上传图像,但它不起作用。

寄存器叶片

代码语言:javascript
复制
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Register') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('register') }}">
                        @csrf

                        <div class="row mb-3">
                            <label for="name" class="col-md-4 col-form-label text-md-end">{{ __('Name') }}</label>

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

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

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

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

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

                        <div class="row mb-3">
                            <label for="image" class="col-md-4 col-form-label text-md-end">{{ __('Image') }}</label>

                            <div class="col-md-6">
                                <input type="file" class="custom-file-input" id="Image" name="image" required>
                                @error('image')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror
                            </div>
                        </div>


                        <div class="row mb-3">
                            <label for="secretword" class="col-md-4 col-form-label text-md-end">{{ __('secretword') }}</label>

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

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

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password">

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

                        <div class="row mb-3">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-end">{{ __('Confirm Password') }}</label>

                            <div class="col-md-6">
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Register') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

用户模型

代码语言:javascript
复制
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Qirolab\Laravel\Reactions\Traits\Reacts;
use Qirolab\Laravel\Reactions\Contracts\ReactsInterface;

class User extends Authenticatable implements MustVerifyEmail, ReactsInterface
{
    use HasApiTokens, HasFactory, Notifiable, Reacts;

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

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

    public function roles()
    {
        return $this
            ->belongsToMany(Role::class)
            ->withTimestamps();
    }

    public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }

    public function authorizeRoles($roles)
    {
        if ($this->hasAnyRole($roles)) {
            return true;
        }
        abort(401, 'This action is unauthorized.');
    }

    public function hasAnyRole($roles)
    {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                if ($this->hasRole($role)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role)
    {
        if ($this->roles()->where('name', $role)->first()) {
            return true;
        }
        return false;
    }
};

用户表

代码语言:javascript
复制
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('secretword');
            $table->string('image');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->integer('reactions')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->integer('reaction')->default(0)->change();
        });
    }
};

RegisterConctroller

代码语言:javascript
复制
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use App\Models\Role;
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'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'secretword' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'image' => ['required','image','mimes:jpeg,png,jpg,gif,svg','max:1000'],
        ]);
    }

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

        if(User::count() > 1){
            $adminRole = Role::where('name', 'like', 'ROLE_USER')->first();
            $newUser->roles()->attach($adminRole->id);
        }else{
            $adminRole = Role::where('name', 'like', 'ROLE_SUPERADMIN')->first();
            $newUser->roles()->attach($adminRole->id);
            $adminRole = Role::where('name', 'like', 'ROLE_USER')->first();
            $newUser->roles()->attach($adminRole->id);
        }

        return $newUser;

    }
}

当我执行dd($data)时,我看到以下内容:

代码语言:javascript
复制
^ array:7 [▼
  "_token" => "Zh1vOo1lcbtA9LkaWBBSVZNvo6gFWDhUaW4qQfjB"
  "name" => "tqjsoahemaqdq"
  "email" => "tqjsoahemaqdq@arxxwalls.com"
  "secretword" => "secretword1"
  "password" => "denden73"
  "password_confirmation" => "denden73"
  "image" => Illuminate\Http\UploadedFile {#1369 ▼
    -test: false
    -originalName: "Screenshot from 2022-08-18 15-07-46.png"
    -mimeType: "image/png"
    -error: 0
    #hashName: null
    path: "/tmp"
    filename: "phpX0fkFo"
    basename: "phpX0fkFo"
    pathname: "/tmp/phpX0fkFo"
    extension: ""
    realPath: "/tmp/phpX0fkFo"
    aTime: 2022-08-25 14:47:03
    mTime: 2022-08-25 14:47:03
    cTime: 2022-08-25 14:47:03
    inode: 30730823
    size: 9104
    perms: 0100600
    owner: 1000
    group: 1000
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
  }
]

首先,注册没有工作,我必须添加enctype=“多部分/表单-数据”后,我添加它。注册工作,但我的印象是,图像不加载。当我这么做的时候,它会显示上面的信息。如何纠正此错误?这样,用户就必须有题词,才能加载图像和加载什么。我不是,但我认为问题在控制器,我如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2022-08-25 17:52:33

这可能对你有用。

更新您的创建方法如下:

代码语言:javascript
复制
/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\Models\User
 */
protected function create(array $data)
{
    $file_extention = $data['image']->getClientOriginalExtension();
    $file_name = time().rand(99,999).'image.'.$file_extention;
    $file_path = $data['image']->move(public_path().'/users/image',$file_name);
    $newUser = User::create([
        'name' => $data['name'],
        'secretword' => $data['secretword'],
        'email' => $data['email'],
        'image' => $file_path, //This will be full path to the image
        'password' => Hash::make($data['password']),
    ]);
    

    if(User::count() > 1){
        $adminRole = Role::where('name', 'like', 'ROLE_USER')->first();
        $newUser->roles()->attach($adminRole->id);
    }else{
        $adminRole = Role::where('name', 'like', 'ROLE_SUPERADMIN')->first();
        $newUser->roles()->attach($adminRole->id);
        $adminRole = Role::where('name', 'like', 'ROLE_USER')->first();
        $newUser->roles()->attach($adminRole->id);
    }

    return $newUser;

}

如果这对你有用的话请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73490402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档