我正在和laravel一起做一个项目。我正在使用Cartalyst-Sentinel。如何在数据库的users表中添加来自first_name+last_name的插件
我为"roles“表添加了slug,但我不知道如何通过添加first_name和last_name来在"users”表的"slug“列中添加值。例如: first_name= "JOHN",last_name="CENA",slug="JOHN-CENA“
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->string('birthday')->nullable();
$table->string('gender')->nullable();
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('slug');
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
$table->unique('slug');
});
DB::table('roles')->insert(array(
array('id'=>1, 'slug'=> 'admin', 'name'=> 'Admin', 'permissions'=> NULL),
array('id'=>2, 'slug'=> 'user', 'name'=> 'User', 'permissions'=> NULL)
)
);发布于 2019-01-19 08:44:06
我不知道为什么首先要在users表中有一个slug列,但是您可以在插入/更新用户时自动设置slug,您可以使用Laravel model events或Laravel observers。您感兴趣的事件是saving事件,该事件在数据库上更新/创建用户之前被调用。
或者,也可以使用Laravel mutators,以便在设置first_name或last_name属性时,也会更新slug属性。
此外,您还可以使用Laravel的辅助方法str_slug()。它可以将字符串转换为slug。
下面是一个包含观察者的示例:
app/Observers/UserObserver.php
namespace App\Observers\UserObserver;
use Cartalyst\Sentinel\Users\EloquentUser;
class UserObserver
{
public function saving(EloquentUser $user)
{
$user->slug = str_slug($user->first_name . ' ' . $user->last_name);
}
}app/Providers/AppServiceProvider.php
namespace App\Providers;
use Cartalyst\Sentinel\Users\EloquentUser;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
EloquentUser::observe(UserObserver::class);
}
}现在,无论你在哪里做类似这样的事情:
$user = Sentinel::register([
'first_name' => 'John',
'last_name' => 'Cena',
'email' => 'JohnCena@example.com'
'password' => 'justanexample'
]);或
$user->save();用户段塞也将被保存。
https://stackoverflow.com/questions/53986732
复制相似问题