Имя пользователя не вставлено и отношения нарушены - PullRequest
0 голосов
/ 16 февраля 2020
public function index()
{
    //
    $users = \App\User::with(['roles','profile'])->get();
    return view('dashboard.users.index',compact('users'));
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
    $roles = \App\Role::all();
    $countries = \App\Country::all();
    return view('dashboard.users.create',compact('countries','roles'));
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
    $user = [
        'username' => $request->username,
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
    ];
    $user = \App\User::create($user);
           $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
    if ($request->hasFile('photo')) 
     $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
 else
    $filename = "profiles/dummy.jpg";
if ($user) {
    $profile = new \App\UserProfile([
        'user_id' => $user->id,
        'city' => $request->city,
        'country_id' => $request->country,
        'photo' => $filename,
        'phone' => $request->phone,
    ]);
    $user->profile()->save($profile);
    $user->roles()->attach($request->roles);
    return redirect()->route('users.index');
}

}

Это контроллер

@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf
    <div class="form-row align-item-center">
        <div class="col-md-12">
            <label for="inputUsername"> Name</label>
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">
        </div>
        <div class="col-md-12">
            <label for="inputName">Full Name</label>
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">
        </div>
        <div class="col-md-12">
            <label for="inputUserEmail">Email</label>
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">
        </div>
        <div class="col-md-12">
            <label for="inputPassword">Password</label>
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">
        </div>
        <div class="col-md-12">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">
        </div>
        <div class="col-md-12">
            <label for="selectCountry">Select Country</label>
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 mt-3">
            <label for="inputCity">City</label>
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">
        </div>
        <div class="col-md-12">
            <label for="selectRoles">Select Roles</label>
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 my-3">
            <label for="inputFileName">Profile Image</label>
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">
        </div>
        <div class="col-md-12">
        <button type="submit" class="btn btn-primary mb-2">Add New User</button>
    </div>
</div>
</form>
@endsection

Это представление

class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

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

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id');
    }
}

Это модель пользователя

class UserProfile extends Model
{
    protected $guard = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}

Это UserProfile Model

class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}

Это Country Model

Я использую этот код, В этом коде не вставляется значение имени пользователя, которое я изменил в миграции, используйте nullable функцию и мигрируйте refre sh, тогда отношения были разорваны, и когда создали пользователя и добавили [user_id] в свойство, доступное для заполнения, чтобы разрешить массовое назначение в [App \ UserProfile]. ошибка

https://gist.github.com/Hammad964/85fb516517f0bc7163885bff167d29e0 это ссылка на github, пожалуйста, решите все проблемы

1 Ответ

0 голосов
/ 16 февраля 2020

Я думаю, это потому, что вы не добавили username в массив $fillable в вашей User модели.

Это должно быть:

protected $fillable = [
    'name', 'email', 'password', 'username',
];

Обновление:

В вашей UserProfile модели. У вас есть строка protected $guard = [];, но laravel ожидает, что она будет protected $guarded = [];

. Благодаря этому все столбцы модели можно назначать по массе, поэтому обычно рекомендуется использовать $fillable подход или, по крайней мере, добавление полей, которые не нужно массово присваивать массиву $guarded, чтобы снизить риск для безопасности вашего приложения.

Надеюсь, это поможет!

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