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)
)
);
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
savingevent, 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
app/Providers/AppServiceProvider.php
Now anywhere you do something like:
or
The user slug would also be saved.