Получение сообщения об ошибке Общая ошибка: 1364 Поле «пол» не имеет значения по умолчанию - PullRequest
0 голосов
/ 01 июля 2019

Я пытаюсь создать регистрацию профиля пользователя.Тем не менее, я получаю ошибки, но я не вижу, что я делаю неправильно.

Общая ошибка: 1364 Поле «пол» не имеет значения по умолчанию

Миграция

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->index();
        $table->string('gender');
        $table->string('initials');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('profession');
        $table->string('specialism');
        $table->string('profession_titulature');
        $table->string('company_name');
        $table->string('country');
        $table->string('city');
        $table->string('postal_code');
        $table->string('street');
        $table->string('house_number');
        $table->string('house_number_addition');
        $table->string('phone_number');
        $table->string('mobile_number');
        $table->longText('description');
        $table->string('agb_code');
        $table->string('big_code');
        $table->boolean('accepted')->default(1);
        $table->boolean('visible')->default(1);
        $table->timestamps();

        // This is foreignkey at the database level
        $table->foreign('user_id')->references('id')->on('users');
    });
}

Запрос

public function rules()
{
    return [
        'gender' => 'required',
        'initials' => '',
        'first_name' => '',
        'last_name' => '',
        'profession' => '',
        'specialism' => '',
        'profession_titulature' => '',
        'company_name' => '',
        'country' => '',
        'city' => '',
        'postal_code' => '',
        'street' => '',
        'house_number' => '',
        'house_number_addition' => '',
        'phone_number' => '',
        'mobile_number' => '',
        'agb_code' => '',
        'big_code' => '',
        'description' => '',
    ];
}

Форма

<form action="{{ route('profile.store') }}" method="post">
    @csrf
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="selectGender">Gender</label>
            <select name="gender" class="form-control" id="selectGender">
                <option value="" disabled>Select gender</option>
                @foreach($profile->activeOptions() as $activeOptionKey => $activeOptionValue)
                    <option value="{{$activeOptionKey}}" {{ $profile->active == $activeOptionValue ? 'selected' : '' }}>
                        {{ $activeOptionValue }}\
                    </option>
                @endforeach
            </select>
            @if($errors->has('gender'))
                <span class="invalid-feedback" style="display: block;" role="alert">
                        <strong>{{ $errors->first('gender') }}</strong>
                    </span>
            @endif
        </div>
        <div class="form-group col-md-6">
            <label for="inputInitials">Initials</label>
            <input name="initials" type="text" class="form-control" id="inputInitials"
                   placeholder="Initials" value="{{old('initials') ?? ''}}">
            @if($errors->has('initials'))
                <span class="invalid-feedback" style="display: block;" role="alert">
                        <strong>{{ $errors->first('initials') }}</strong>
                    </span>
            @endif
        </div>
        <!-- I have not put the whole form here... -->
        <button type="submit" class="btn btn-primary">Opslaan</button>
    </div>
</form>

Модель

class Profile extends Model
{
    protected $guarded = [];
}

Контроллер

public function create()
{
    $profile = new Profile();
    return view('pages.profile.create', compact('profile'));
}


public function store(StoreProfileRequest $request)
{
    $validated = $request->validated();
    Profile::create(['user_id' => Auth::id()], $validated);

    return redirect('/');
}

1 Ответ

0 голосов
/ 03 июля 2019

Я думаю, что проблема здесь

 Profile::create(['user_id' => Auth::id()], $validated);

Eloquent create метод требует ассоциированного массива, и вы помещаете сюда два массива:)

Но для создания модели с массовым назначением вам необходимо указать атрибут $fillable для модели.

Пожалуйста, проверьте документацию по этому вопросу: https://laravel.com/docs/5.8/eloquent#mass-assignment

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...