[英]Add [username] to fillable property to allow mass assignment on [App/post]
[英]"Add [name] to fillable property to allow mass assignment on [Illuminate\Foundation\Auth\User]."
User.php代码,这里不管我用fillable还是gaurded,都报一样的错。
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
*@var array
*/
// protected $fillable = [
// 'name',
// 'email',
// 'password',
// ];
protected $guarded = [];
/**
* 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',
];
}
UserController.php代码,这里我试过批量赋值
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\User;
use Illuminate\Database\Eloquent\Model;
class UserController extends Controller
{
public function index()
{
$data = [
'name' => 'elon',
'email' => 'elon@gmail.com',
'password' => 'password',
];
User::create($data);
$user = User::all();
return $user;
}
}
您似乎没有从 UserController.php 中的正确命名空间导入用户 class
您正在使用
use Illuminate\Foundation\Auth\User;
利用
use App\Models\User;
反而。
编辑:
$fillable 在这种情况下不是问题,因为 $guarded 设置为一个空数组,它允许所有字段都可以通过 create 方法进行批量分配。 Eloquent 质量分配
提供的代码有两个问题:
User
class 中的$fillable
Model
属性来批量分配 Model 属性:<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
*@var array
*/
protected $fillable = [
'name',
'email',
'password',
];
protected $guarded = [];
/**
* 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',
];
}
class
:<?php
namespace App\Http\Controllers;
use App\Models\User; // <-- corrected line
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
class UserController extends Controller
{
public function index()
{
$data = [
'name' => 'elon',
'email' => 'elon@gmail.com',
'password' => 'password',
];
User::create($data);
$user = User::all();
return $user;
}
}
在UserController.php
尝试使用
use App\Models\User;
在 laravel 7 这对我有用:
use App\User;
对我来说,我必须使用ctrl + c
停止终端中的服务器,并使用php artisan serve
重新启动服务器它对我有用。
我发现这在 laravel 8 中对我有帮助,这在所有版本中都可以正常工作,因为如果我们多次导入 class 并且它会自动导入另一个,所以请检查您是否导入了这个 class 或另一个。
use App\Models\User;
通过在我的 model 中添加这个
受保护的 $guarded = [];
它使我免于痛苦,谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.