I have 2 model in laravel 5.5
Article.php class with 2 function:
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function path()
{
return "/$this->slug";
}
Category.php
public function childs() {
return $this->hasMany('App\Category','parent_id','id') ;
}
categories table:
id / article_id / parent_id / name
Now for example,for this code in view: {{ $article->path() }}
it prints: `example.com/article_slug`
But I want simething like this:
example.com/parentCategory/subCategory-1/.../subCategory-n/article_slug
How can I do it in path()
function? Is it possible?
I'm assuming your question is asking how you can generate uri's for categories that can have an unlimited amount of children via their slugs.
How I would go about tackling something like this is by using a hierarchical data pattern within MySQL which will allow you to get a list of descendants / ancestors by performing one query. There are numerous ways to implement this, but for the purpose of this explanation I'm going to explain how to do it using the nested set pattern. More specifically, I'll be giving demonstrating how to do this using lazychaser's nested set package.
use Kalnoy\Nestedset\NestedSet;
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
NestedSet::columns($table);
$table->timestamps();
});
The nested set columns will add _lft
, _rgt
, and parent_id
columns to your table. I would recommend you do some research on how the nested set model works in order to understand what the left and right columns are used for.
use Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use NodeTrait;
//
}
Now you can create a child category like so:
$parentCategory = Category::first();
$parentCategory->children()->create([
'name' => 'Example Category'
]);
This means that on a deeply nested category you can do:
$categories = Category::ancestorsAndSelf($article->category_id);
This will return all ancestors of the above category, then to get the uri you can do something like:
$uri = $categories->pluck('slug')->implode('/') . '/' . $article->slug;
You need to use the Sluggable
Trait at the top of your model like so :
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'
]
];
}
}