If you want to populate '_created_by' when it is defined as guarded, you cannot assign it from a form, as stated above. Instead, you have to write a code to assign a default value. For example, if _created_by is ALWAYS the currently authenticated user, you can do this:
Create a trait named CreatedByTrait with following content:
<?php
declare(strict_types=1);
namespace App\Traits;
trait CreatedByTrait
{
/**
* Boot the trait for a model.
*
*/
public static function bootCreatedByTrait(): void
{
if (auth()->check()) {
static::creating(function ($model): void {
$model->created_by = auth()->id();
});
}
}
}
Then, in the model where you have defined _created_by as guarded, include the trait in the beginning:
<?php
declare(strict_types=1);
namespace App\Models;
use App\Traits\CreatedByTrait;
class SomeModel extends Model
{
use CreatedByTrait;
}
With the above code, every time when you create a new record for SomeModel the field for _created_by will be auto-populated with the ID of the currently authenticated user.
If you are suing Livewire, same code can be used for #[Locked] properties.