0

Смотрел видеоурок Laravel 9 и Vue 3 SPA интернет магазин 7. CRUD по пользователям с 9:00-10:50. Получаю следующую ошибку

введите сюда описание изображения

введите сюда описание изображения

Привожу код

laravelvue3shop\app\Models\User.php

<?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; use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable;

const GENDER_MALE=1;
const GENDER_FEMALE=2;

protected $table='users';
protected $guarded=false;

static function getGenders() {
    return [
       self::GENDER_MALE =&gt; 'Мужской',
       self::GENDER_FEMALE =&gt; 'Женский'
    ];
}

public function getGenderTitleAttribute() {
    return self::getGenders()[$this-&gt;gender];
}

/**
 * The attributes that are mass assignable.
 *
 * @var array&lt;int, string&gt;
 */
protected $fillable = [
    'name',
    'email',
    'password',
];

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

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

}

laravelvue3shop\database\migrations\2022_09_07_084830_add_surname_patronymic_age_address_gender_to_users_table.php

<?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::table('users', function (Blueprint $table) { $table->string('surname')->nullable(); $table->string('patronymic')->nullable(); $table->integer('age')->nullable(); $table->string('address')->nullable(); $table->unsignedSmallInteger('gender')->nullable(); }); }

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table-&gt;dropColumn('gender');
        $table-&gt;dropColumn('address');
        $table-&gt;dropColumn('age');
        $table-&gt;dropColumn('patronymic');
        $table-&gt;dropColumn('surname');
    });
}

};

laravelvue3shop/resources/views/user/create.blade.php

@extends('layouts.main')

@section('content') <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Добавить пользователя</h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item active">Главная</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header -->

&lt;!-- Main content --&gt;
&lt;section class="content"&gt;
    &lt;div class="container-fluid"&gt;
        &lt;!-- Small boxes (Stat box) --&gt;
        &lt;div class="row"&gt;
            &lt;form action="{{ route('user.store') }}" method="post"&gt;
                @csrf

                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("name") }}" name="name" class="form-control" placeholder="Имя"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="email" value="{{ old("email") }}" name="email" class="form-control" placeholder="Email"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("password") }}" name="password" class="form-control" placeholder="Пароль"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("password_confirmation") }}" name="password_confirmation" class="form-control" placeholder="Подтверждение пароля"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("surname") }}" name="surname" class="form-control" placeholder="Фамилия"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("patronymic") }}" name="patronymic" class="form-control" placeholder="Отчество"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("age") }}" name="age" class="form-control" placeholder="Возраст"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ old("address") }}" name="address" class="form-control" placeholder="Адрес"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;select name="gender" class="custom-select form-control" id="exampleSelectBorder"&gt;
                        &lt;option disabled selected&gt;Пол&lt;/option&gt;
                        &lt;option {{ old('gender') == 1 ? ' selected' : '' }} value="1"&gt;Мужской&lt;/option&gt;
                        &lt;option {{ old('gender') == 2 ? ' selected' : '' }} value="2"&gt;Женский&lt;/option&gt;
                    &lt;/select&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="submit" class="btn btn-primary" value="Добавить"&gt;
                &lt;/div&gt;

            &lt;/form&gt;
        &lt;/div&gt;
        &lt;!-- /.row --&gt;
    &lt;/div&gt;&lt;!-- /.container-fluid --&gt;
&lt;/section&gt;
&lt;!-- /.content --&gt;

@endsection

laravelvue3shop/resources/views/user/edit.blade.php

@extends('layouts.main')

@section('content') <!-- Content Header (Page header) --> <div class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1 class="m-0">Редактировать пользователя</h1> </div><!-- /.col --> <div class="col-sm-6"> <ol class="breadcrumb float-sm-right"> <li class="breadcrumb-item active">Главная</li> </ol> </div><!-- /.col --> </div><!-- /.row --> </div><!-- /.container-fluid --> </div> <!-- /.content-header -->

&lt;!-- Main content --&gt;
&lt;section class="content"&gt;
    &lt;div class="container-fluid"&gt;
        &lt;!-- Small boxes (Stat box) --&gt;
        &lt;div class="row"&gt;
            &lt;form action="{{ route('user.update', $user-&gt;id) }}" method="post"&gt;
                @csrf
                @method('patch')
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ $user-&gt;name ?? old("name") }}" name="name" class="form-control" placeholder="Имя"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ $user-&gt;surname ?? old("surname") }}" name="surname" class="form-control" placeholder="Фамилия"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ $user-&gt;patronymic ?? old("patronymic") }}" name="patronymic" class="form-control" placeholder="Отчество"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ $user-&gt;age ?? old("age") }}" name="age" class="form-control" placeholder="Возраст"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="text" value="{{ $user-&gt;address ?? old("address") }}" name="address" class="form-control" placeholder="Адрес"&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;select name="gender" class="custom-select form-control" id="exampleSelectBorder"&gt;
                        &lt;option disabled selected&gt;Пол&lt;/option&gt;
                        &lt;option {{ $user-&gt;gender == 1 || old('gender') == 1 ? ' selected' : '' }} value="1"&gt;Мужской&lt;/option&gt;
                        &lt;option {{ $user-&gt;gender == 2 || old('gender') == 2 ? ' selected' : '' }} value="2"&gt;Женский&lt;/option&gt;
                    &lt;/select&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                    &lt;input type="submit" class="btn btn-primary" value="Добавить"&gt;
                &lt;/div&gt;

            &lt;/form&gt;
        &lt;/div&gt;
        &lt;!-- /.row --&gt;
    &lt;/div&gt;&lt;!-- /.container-fluid --&gt;
&lt;/section&gt;
&lt;!-- /.content --&gt;

@endsection

Подскажите, в чем ошибка в обращении к $this->gender.

1 Answers1

1

$this->gender - пустой. Соответственно конструкция self::getGenders()[$this->gender] не работает, так как в массиве нет ключа с пустым значением

  • в $this->gender лежит значение, которое вводится в laravelvue3shop/resources/views/user/create.blade.php в select-е. Оно не пустое. – vladwebsearch Sep 11 '22 at 06:45
  • оно пустое........как минимум сам текст ошибки говорит об этом....... если хочется убедиться в этом - https://ru.stackoverflow.com/a/701146/191482 вот отладочка в помощь – Алексей Шиманский Sep 11 '22 at 06:55
  • при выборе значения в <option disabled selected>Пол</option> что будет в переменной? какое значение? – Алексей Шиманский Sep 11 '22 at 06:57
  • также стоит обратить внимание, что из формы прилетают строковые значения, а в ключах массива - числа – Алексей Шиманский Sep 11 '22 at 06:59