【问题标题】:How to add slug in Cartalyst-Sentinel by adding first_name and last_name?如何通过添加 first_name 和 last_name 在 Cartalyst-Sentinel 中添加 slug?
【发布时间】:2019-05-27 22:39:01
【问题描述】:

我正在用 laravel 做一个项目。我正在使用 Cartalyst-Sentinel。如何在数据库中的用户表中添加来自 first_name+last_name 的 slug

我为“角色”表添加了 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)
        )
    );

【问题讨论】:

    标签: laravel cartalyst-sentinel


    【解决方案1】:

    我不知道你为什么首先要在 users 表中有一个 slug 列,但是你可以在插入/更新用户时自动设置 slug,你可以使用 Laravel model events 或 @987654322 @。您感兴趣的事件是 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();
    

    用户 slug 也会被保存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多