【问题标题】:When I Trying to create a new User I cannot当我尝试创建新用户时,我不能
【发布时间】:2020-12-22 05:10:56
【问题描述】:

我尝试使用表 Perfiles(profiles) 中的外键创建一个名为 Usuarios(Users) 的 CRUD,外键是 Profiles 中的 id,但我不知道如何使用 select

这是我的 FORM.BLADE.PHP

<select name="idPerfil" id="idPerfil" class="form-control">
        <option value="">Eliga un nombre de perfil </option>
    @foreach ($perfiles as $perfil)
    
    <option value="{{ $perfil['id'] }}" 
    
 @if ($perfil->id === $usuario->idPerfil)
    selected
        
    @endif
    
    > {{ $perfil['NombrePerfil'] }}
        
    </option>      
        @endforeach
        </select>

PerfilesContoller.php

 public function edit($id)
{
    
    $perfil= Perfiles::findOrFail($id);

    return view('perfiles.edit',compact('perfil'));
}

公共函数 create() {

    return view('perfiles.create');

}

这是我的 USUARIOSCONTROLLER.PHP

public function create()
    {
        //
        $perfiles = Perfiles::all();

        return view('usuarios.create',compact('perfiles'));
    }

公共函数编辑($id) { //

        $usuario= Usuarios::findOrFail($id);
        $perfiles = Perfiles::all();

        return view('usuarios.edit',compact('usuario','perfiles'));
    }

表格文件

public function up()
{
    Schema::create('perfiles', function (Blueprint $table) {

        $table->increments('id');
        $table->string('NombrePerfil')->unique();
        $table->timestamps();
        
    });
}

桌子上的用料

 public function up()
{
    
    
    Schema::create('usuarios', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('idPerfil');
        $table->string('Nombre');
        $table->string('UserName')->unique();
        $table->string('Email')->unique();
        $table->string('Password');
        $table->foreign('idPerfil')->references('id')->on('perfiles');
        $table->rememberToken();
        $table->timestamps();
    });
}

【问题讨论】:

  • 欢迎来到 SO ... 您尝试创建新用户但不能创建新用户的代码在哪里?您显示的唯一视图似乎是用于编辑用户,而不是创建
  • 我有一个 Form.blade.php、create.blade.php 和 edit.blade.php,Form.blade 与 create 和 edit 共享。

标签: php laravel laravel-6 laravel-7


【解决方案1】:

对于初学者,我认为您在访问主键时就好像 perfil 在某个时候是一个数组,然后在另一个时候将其视为一个对象,您这样做:$perfil['id'] 而不是这个:$perfil-&gt;id。尝试像这样构造你的刀片:

<select name="idPerfil" id="idPerfil" class="form-control">
    <option value="">Eliga un nombre de perfil </option>
    @foreach ($perfiles as $perfil)
    
    <option value="{{ $perfil->id }}" 
    
        @if ($perfil->id === $usuario->idPerfil) selected @endif> 
       
       {{ $perfil->NombrePerfil }}
        
    </option>      
    @endforeach
</select>

【讨论】:

  • 您可以通过任何一种方式访问​​模型的属性,它们可能应该坚持一个,但在功能上没有区别
  • 真的...他的问题有很多问题,首先我不确定他在模型中声明关系时指定了主键列,因为如果他没有 laravel 将默认为约定perfil_id 所以idPerfil 不会工作。其次,profile 应该是 user 的子代,而不是相反,不是说它最终不会起作用……我只是消除了最明显的部分。
  • 你想看看我的桌子吗?
  • 我已经编辑了我的问题
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 2014-03-19
  • 2017-11-13
  • 1970-01-01
  • 2019-01-15
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多