V
V
Vitaly Sherstobitov2021-02-18 23:39:46
Laravel
Vitaly Sherstobitov, 2021-02-18 23:39:46

Uploading image when registering Laravel?

I'm trying to upload photos when registering. Form code:

<div class="form-group row">
        <label for="passport" class="col-12">{{ __('Фото паспорта') }}</label>
        <div class="col-12">
            <input id="passport" type="file" class="form-control" name="passport">
        </div>
    </div>
    <div class="form-group row">
        <label for="passport_head" class="col-12">{{ __('Фото с паспортом в руках') }}</label>
        <div class="col-12">
            <input id="passport_head" type="file" class="form-control" name="passport_head">
        </div>
    </div>

Code in the User.php model
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// Эти два из Media Library
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;

class User extends Authenticatable implements HasMedia
{
    use HasFactory, Notifiable;

    use HasMediaTrait;

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

    /**
     * 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',
    ];
}

Code in the controller RegisterController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\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, [
            'first_name' => ['required', 'string', 'max:255'],
            'name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'passport' => ['required', 'string', 'max:255'],
            'passport_head' => ['required', 'string', 'max:255'],
            'card' => ['required', 'string', 'max:255'],
        ]);
    }

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

        if (isset($data['passport'])) {
            $user->addMediaFromRequest('passport')->toMediaCollection('media');
        }

        if (isset($data['passport_head'])) {
            $user->addMediaFromRequest('passport_head')->toMediaCollection('media');
        }

        return $user;
    }
}

When loading, it gives an error:
Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\RequestDoesNotHaveFile
The current request does not have a file in a key named `passport`

What's the matter? Why is photo field data lost?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniel, 2021-02-20
@daniil46

In the validator, replace

...
'passport' => ['required', 'string', 'max:255'],
'passport_head' => ['required', 'string', 'max:255'],
...

on the
...
'passport' => ['required', 'image'],
'passport_head' => ['required', 'image'],
...

If you want to check the file size as well, then add 'max:4096'. Specify the size in bytes
PS Pass the data from the form as Request $data
PPS It is better to do the validator separately

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question