PHP code example of quocphongdn / eloquent-sluggable
1. Go to this page and download the library: Download quocphongdn/eloquent-sluggable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
quocphongdn / eloquent-sluggable example snippets
use Cviebrock\EloquentSluggable\Sluggable;
class Post extends Model
{
use Sluggable;
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
$post = new Post([
'title' => 'My Awesome Blog Post',
]);
$post->save();
echo $post->slug;
$post = new Post([
'title' => 'My Awesome Blog Post',
]);
$post->save();
// $post->slug is "my-awesome-blog-post"
$newPost = $post->replicate();
// $newPost->slug is "my-awesome-blog-post-1"
use \Cviebrock\EloquentSluggable\Services\SlugService;
$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post');
$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post', ['unique' => false]);
Post::registerModelEvent('slugging', function($post) {
if ($post->someCondition()) {
// the model won't be slugged
return false;
}
});
Post::registerModelEvent('slugged', function($post) {
Log::info('Post slugged: ' . $post->getSlug());
});
class Book extends Eloquent
{
use Sluggable;
protected $fillable = ['title'];
public function sluggable() {
return [
'slug' => [
'source' => ['author.name', 'title']
]
];
}
public function author() {
return $this->belongsTo(Author::class);
}
}
...
class Author extends Eloquent
{
protected $fillable = ['name'];
}
class Person extends Eloquent
{
use Sluggable;
public function sluggable()
{
return [
'slug' => [
'source' => 'fullname'
]
];
}
public function getFullnameAttribute() {
return $this->firstname . ' ' . $this->lastname;
}
}