Laravel Регистрационная форма не публикуется в базе данных - PullRequest
1 голос
/ 16 апреля 2020

Я очень плохо знаком с Laravel, поэтому, пожалуйста, потерпите меня.

Я установил пользовательские леса с помощью команды Auth.

Мне нужно было добавить поля в форму регистрации, поэтому я обновил базу данных таблицами и столбцами с помощью команды миграции.

Затем я отредактировал остальные файлы с помощью дополнительных полей (см. Ниже) , Когда я заполняю форму и отправляю ее, страница перезагружается, и данные не отправляются в базу данных.

Это текущая ошибка, которую я получаю: «Адрес2 должен быть строкой». Я вижу эту ошибку, только когда у меня есть @dump ($ errors) в представлении регистрации.

Я попытался установить для поля значение "nullable", но затем я получаю ошибку MySQL, говорящую, что это возможно ' ноль. Установка нескольких других значений в nullable, казалось, исправляла некоторые ошибки, но я чувствую, что это может быть неправильный подход. Как я уже сказал, я все еще новичок в Laravel и пытаюсь понять.

Помощь очень ценится. Спасибо!

Файл миграции

    <?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('prefix');
            $table->string('first_name');
            $table->string('middle_name');
            $table->string('last_name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('address1');
            $table->string('address2');
            $table->string('city');
            $table->string('state');
            $table->string('zipcode');
            $table->string('phone_home');
            $table->string('phone_mobile');
            $table->string('phone_work');
            $table->string('phone_other');
            $table->string('referred_by');
            $table->date('birth_date');
            $table->string('birth_city');
            $table->string('birth_state');
            $table->string('birth_country');
            $table->string('alien_number');
            $table->string('ssn');
            $table->string('dl_number');
            $table->boolean('petitions_filed')->nullable();
            $table->boolean('crime_victim')->nullable();
            $table->boolean('been_arrested')->nullable();
            $table->string('bio', 2500);
            $table->string('position');
            $table->integer('role');
            $table->string('avatar_image')->default('avatarDefault.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

register.blade. php

@dump($errors)
@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">{{ __('Create New Consultation') }}</div>

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

                        <div class="form-group row">
                            <div class="col">
                                <label for="prefix" class="col-form-label text-md-right">{{ __('Prefix') }}</label>
                                <select id="prefix" type="text" class="form-control" name="prefix" value="{{ old('prefix') }}" autocomplete="prefix" autofocus>
                                    <option>Mr.</option>
                                    <option>Mrs.</option>
                                    <option>Ms.</option>
                                </select>
                            </div>

                            <div class="col">
                                <label for="first_name" class="col-form-label text-md-right">{{ __('First Name') }}</label>
                                <input id="first_name" type="text" class="form-control @error('first_name') is-invalid @enderror" name="first_name" value="{{ old('first_name') }}" required autocomplete="first_name" autofocus>

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

                            <div class="col">
                                <label for="middle_name" class="col-form-label text-md-right">{{ __('Middle Name') }}</label>
                                <input id="middle_name" type="text" class="form-control" name="middle_name" value="{{ old('middle_name') }}" autocomplete="middle_name" autofocus>
                            </div>

                            <div class="col">
                                <label for="last_name" class="col-form-label text-md-right">{{ __('Last Name') }}</label>
                                <input id="last_name" type="text" class="form-control" name="last_name" value="{{ old('last_name') }}" required autocomplete="last_name" autofocus>

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

                        <div class="form-group row">
                            <div class="col">
                                <label for="email" class="col-form-label text-md-right">{{ __('E-Mail') }}</label>

                                <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 class="col">
                                <label for="referred_by" class="col-form-label text-md-right">{{ __('Referred by') }}</label>
                                <input id="referred_by" type="text" class="form-control" name="referred_by" value="{{ old('referred_by') }}" autocomplete="referred_by" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="address1" class="col-form-label text-md-right">{{ __('Address Line 1') }}</label>
                                <input id="address1" type="text" class="form-control" name="address1" value="{{ old('address1') }}" autocomplete="address1" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="address2" class="col-form-label text-md-right">{{ __('Address Line 2') }}</label>
                                <input id="address2" type="text" class="form-control" name="address2" value="{{ old('address2') }}" autocomplete="address2" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="city" class="col-form-label text-md-right">{{ __('City') }}</label>
                                <input id="city" type="text" class="form-control" name="city" value="{{ old('city') }}" autocomplete="city" autofocus>
                            </div>

                            <div class="col">
                                <label for="state" class="col-form-label text-md-right">{{ __('State') }}</label>
                                <select id="state" type="text" class="form-control" name="state" value="{{ old('state') }}" autocomplete="state" autofocus>
                                    <option value="AL">Alabama</option>
                                    <option value="AK">Alaska</option>
                                    <option value="AZ">Arizona</option>
                                    <option>etc...</option>
                                </select>
                            </div>

                            <div class="col">
                                <label for="zipcode" class="col-form-label text-md-right">{{ __('Zipcode') }}</label>
                                <input id="zipcode" type="text" class="form-control" name="zipcode" value="{{ old('zipcode') }}" autocomplete="zipcode" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="phone_home" class="col-form-label text-md-right">{{ __('Home Phone') }}</label>
                                <input id="phone_home" type="text" class="form-control" name="phone_home" value="{{ old('phone_home') }}" autocomplete="phone_home" autofocus>
                            </div>
                            <div class="col">
                                <label for="phone_mobile" class="col-form-label text-md-right">{{ __('Mobile Phone') }}</label>
                                <input id="phone_mobile" type="text" class="form-control" name="phone_mobile" value="{{ old('phone_mobile') }}" autocomplete="phone_mobile" autofocus>
                            </div>
                            <div class="col">
                                <label for="phone_work" class="col-form-label text-md-right">{{ __('Work Phone') }}</label>
                                <input id="phone_work" type="text" class="form-control" name="phone_work" value="{{ old('phone_work') }}" autocomplete="phone_work" autofocus>
                            </div>
                            <div class="col">
                                <label for="phone_other" class="col-form-label text-md-right">{{ __('Other') }}</label>
                                <input id="phone_other" type="text" class="form-control" name="phone_other" value="{{ old('phone_other') }}" autocomplete="phone_other" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="birth_date" class="col-form-label text-md-right">{{ __('Date of Birth') }}</label>
                                <input id="birth_date" type="date" class="form-control" name="birth_date" value="{{ old('birth_date') }}" autocomplete="birth_date" autofocus>                                
                            </div>

                            <div class="col">
                                <label for="birth_city" class="col-form-label text-md-right">{{ __('City of Birth') }}</label>
                                <input id="birth_city" type="text" class="form-control" name="birth_city" value="{{ old('birth_city') }}" autocomplete="birth_city" autofocus>
                            </div>

                            <div class="col">
                                <label for="birth_state" class="col-form-label text-md-right">{{ __('State of Birth') }}</label>
                                <input id="birth_state" type="text" class="form-control" name="birth_state" value="{{ old('birth_state') }}" autocomplete="birth_state" autofocus>
                            </div>

                            <div class="col">
                                <label for="birth_country" class="col-form-label text-md-right">{{ __('Country of Birth') }}</label>
                                <input id="birth_country" type="text" class="form-control" name="birth_country" value="{{ old('birth_country') }}" autocomplete="birth_country" autofocus>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col">
                                <label for="bio" class="col-form-label text-md-right">{{ __('Bio') }}</label>
                                <textarea id="bio" type="text" class="form-control" name="bio" value="{{ old('bio') }}" autocomplete="bio" autofocus placeholder="Tell us a little bit about yourself here..."></textarea>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="alien_number" class="col-form-label text-md-right">{{ __('Alien Number') }}</label>
                                <input id="alien_number" type="text" class="form-control" name="alien_number" value="{{ old('alien_number') }}" autocomplete="alien_number" autofocus>
                            </div>

                            <div class="col">
                                <label for="ssn" class="col-form-label text-md-right">{{ __('SSN') }}</label>
                                <input id="ssn" type="text" class="form-control" name="ssn" value="{{ old('ssn') }}" autocomplete="ssn" autofocus>
                            </div>

                            <div class="col">
                                <label for="dl_number" class="col-form-label text-md-right">{{ __('Drivers License Number') }}</label>
                                <input id="dl_number" type="text" class="form-control" name="dl_number" value="{{ old('dl_number') }}" autocomplete="dl_number" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="petitions_filed" class="col-form-label text-md-right">{{ __('Have Any Petitions Filed?') }}</label><br clear="all" />
                                <label>Yes</label>
                                <input id="petitions_filed" type="radio" class="form-control" name="petitions_filed" value="1" autocomplete="petitions_filed" autofocus>
                                <label>No</label> 
                                <input id="petitions_filed" type="radio" class="form-control" name="petitions_filed" value="0" autocomplete="petitions_filed" autofocus>
                            </div>

                            <div class="col">
                                <label for="crime_victim" class="col-form-label text-md-right">{{ __('Been a Victim of a Crime?') }}</label><br clear="all" />
                                <label>Yes</label>
                                <input id="crime_victim" type="radio" class="form-control" name="crime_victim" value="1" autocomplete="crime_victim" autofocus>
                                <label>No</label> 
                                <input id="crime_victim" type="radio" class="form-control" name="crime_victim" value="0" autocomplete="crime_victim" autofocus>
                            </div>

                            <div class="col">
                                <label for="been_arrested" class="col-form-label text-md-right">{{ __('Ever Been Arrested?') }}</label><br clear="all" />
                                <label>Yes</label>
                                <input id="been_arrested" type="radio" class="form-control" name="been_arrested" value="1" autocomplete="been_arrested" autofocus>
                                <label>No</label> 
                                <input id="been_arrested" type="radio" class="form-control" name="been_arrested" value="0" autocomplete="been_arrested" autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col">
                                <label for="password" class="col-form-label text-md-right">{{ __('Create Password') }}</label>
                                <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

                                <label for="password-confirm" class="col-form-label text-md-right">{{ __('Confirm Password') }}</label>
                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
                            </div>

                            <div class="col">
                                <label>Avatar Image</label><br clear="all" />
                                <small>Upload a picture or take a photo on your device.</small>
                                <input id="avatar_image" type="file" class="form-control" name="avatar_image" autocomplete="avatar_image">
                            </div>                       
                        </div>
                        <br />
                        <br />
                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Create Consultation') }}
                                </button>
                                <br />
                                <br />
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Пользователь. php

<?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 = [
        'prefix',
        'first_name', 
        'middle_name', 
        'last_name', 
        'email', 
        'password',
        'address1', 
        'address2', 
        'city', 
        'state', 
        'zipcode', 
        'phone_home', 
        'phone_mobile', 
        'phone_work', 
        'phone_other', 
        'referred_by', 
        'birth_date', 
        'birth_city', 
        'birth_state', 
        'birth_country', 
        'alien_number', 
        'ssn', 
        'dl_number', 
        'petitions_filed', 
        'crime_victim', 
        'been_arrested', 
        'bio', 
        'avatar_image',
    ];

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

RegisterController. php

<?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
{

    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, [
            'prefix' => ['string', 'max:10', 'nullable'],
            'first_name' => ['required', 'string', 'max:255'],
            'middle_name' => ['string', 'max:255', 'nullable'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'address1' => ['string', 'max:255'],
            'address2' => ['string', 'max:255'],
            'city' => ['string', 'max:255', 'nullable'],
            'state' => ['string', 'max:255', 'nullable'],
            'zipcode' => ['string', 'max:255', 'nullable'],
            'phone_home' => ['string', 'max:20', 'nullable'],
            'phone_mobile' => ['string', 'max:20', 'nullable'],
            'phone_work' => ['string', 'max:20', 'nullable'],
            'phone_other' => ['string', 'max:20', 'nullable'],
            'referred_by' => ['string', 'max:255', 'nullable'],
            'birth_date' => ['date', 'nullable'],
            'birth_city' => ['string', 'max:255', 'nullable'],
            'birth_state' => ['string', 'max:255', 'nullable'],
            'birth_country' => ['string', 'max:255', 'nullable'],
            'alien_number' => ['string', 'max:255', 'nullable'],
            'ssn' => ['string', 'max:20', 'nullable'],
            'dl_number' => ['string', 'max:255', 'nullable'],
            'petitions_filed' => ['boolean', 'nullable'],
            'crime_victim' => ['boolean', 'nullable'],
            'been_arrested' => ['boolean', 'nullable'],
            'bio' => ['string', 'max:2500', 'nullable'],
            'avatar_image' => ['string', 'nullable'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'prefix' => $data['prefix'],
            'first_name' => $data['first_name'],
            'middle_name' => $data['middle_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'address1' => $data['address1'],
            'address2' => $data['address2'],
            'city' => $data['city'],
            'state' => $data['state'],
            'zipcode' => $data['zipcode'],
            'phone_home' => $data['phone_home'],
            'phone_mobile' => $data['phone_mobile'],
            'phone_work' => $data['phone_work'],
            'phone_other' => $data['phone_other'],
            'referred_by' => $data['referred_by'],
            'birth_date' => $data['birth_date'],
            'birth_city' => $data['birth_city'],
            'birth_state' => $data['birth_state'],
            'birth_country' => $data['birth_country'],
            'alien_number' => $data['alien_number'],
            'ssn' => Hash::make($data['ssn']),
            'dl_number' => $data['dl_number'],
            'petitions_filed' => $data['petitions_filed'],
            'crime_victim' => $data['crime_victim'],
            'been_arrested' => $data['been_arrested'],
            'bio' => $data['bio'],
            'avatar_image' => $data['avatar_image'],
        ]);
    }
}

1 Ответ

1 голос
/ 16 апреля 2020

Прежде всего, Хорошая попытка.

"Адрес2 должен быть строкой." означает, что поле address2 является обязательным и исключение выдается из серверной части.

Решение:

В вашем случае

  • Обновите файл миграции. like-

Modified migration

  • Правильно установите проверку для обязательных полей в вашем файле "register.blade. php".
  • Обновите функцию валидатора в файле RegisterController. like-

Modified validator function in RegisterController

  • Если в вашей базе данных есть таблица 'users', вы можете изменить любое поле или выполнить команду refre sh миграция для обновленной базы данных.

php artisan migrate:refresh

Надеюсь, это будет полезно для вас.

...