php - "Add [name] to fillable property to allow mass assignment on [Illuminate\Foundation\Auth\User]."

标签 php laravel laravel-8 mass-assignment

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 中的正确命名空间导入用户类

您正在使用

use Illuminate\Foundation\Auth\User;

使用

use App\Models\User;

相反。

编辑:

$fillable 在这种情况下不是问题,因为 $guarded 被设置为一个空数组,它允许所有字段通过 create 方法进行批量分配。 Eloquent mass assignment

关于php - "Add [name] to fillable property to allow mass assignment on [Illuminate\Foundation\Auth\User].",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65481253/

相关文章:

php - 根据设备在子域上自动重定向

php - Paypal API - CURRENCY_NOT_ALLOWED

mysql - Laravel 从更新查询中获取记录 ID

php - Laravel 8,如何在后台运行作业(脚本)?

php - 显示结果并隐藏重复项

javascript - 如何制作一个在用户页面(他是管理员)上安装页面选项卡的 Facebook 应用程序?

php - Laravel:动态查询按 api 排序

php - 有没有办法在模式关闭之前(在计时器 4 秒内)将信息保存到 mysql,而不使用提交按钮

laravel-8 - 社会名流拉拉维尔。如何获取自定义参数?

php - Laravel 8 |登录后根据角色重定向