0

I am doing a project with laravel. And I am using Cartalyst-Sentinel with it. How can I add slug from first_name+last_name in users table from database

I added slug for "roles" table but I don't know How can I add values in "slug" columns in the "users" table by adding first_name and last_name. ex: 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)
        )
    );

1 Answers1

0

I'm not sure why you would want to have a slug column in the users table in the first place, but you can set the slug automatically when you insert/update a user, you can use Laravel model events or Laravel observers. The event you're interested in is the saving event, which gets called just before updating/creating the user on the database.

Alternatively, you can also use Laravel mutators so that when the first_name, or last_name property is set, the slug property is also updated.

In addition, you can make use of Laravel's helper method str_slug(). Which can convert a string into a slug.

Below is an example with observers:

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);
    }
}

Now anywhere you do something like:

$user = Sentinel::register([
    'first_name' => 'John',
    'last_name' => 'Cena',
    'email' => 'JohnCena@example.com'
    'password' => 'justanexample'
]);

or

$user->save();

The user slug would also be saved.

MTran
  • 1,799
  • 2
  • 17
  • 21