Reputation: 336
I have categories table in my application and it works just fine but i wonder how to get subcategories for that as well?
currently what I have is:
Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function ads(){
return $this->hasMany(Ad::class);
}
}
Category Migration:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
}
My Post Model:
public function category(){
return $this->belongsTo(Category::class);
}
PS: I know I have to make new table and call for foreign key of category_id
for subcategories but what makes me confuse is the relationships and also how to select them in front-end so category and subcategories all shows in one drop down to user (like WP)?
Upvotes: 0
Views: 1384
Reputation: 1672
i really don't understand well what you're trying to do .. but if you're trying to add both categories and subcategories in one dropdown i assume this is what you wanted:
let's say you already have done the relationship .. in your controller
$categories = Category::with('sub_categories')->get();
return view('page',compact('categories'));
now we got all the categories and it's corresponding sub-categories .. in your blade all you have to do is
<select name="categories">
@foreach($categories as $categ)
<optgroup label="{{ $categ->name }}">
@foreach($categ->sub_categories as $sub)
<option value="{{ $sub->id }}">{{ $sub->name }}</option>
@endforeach
</optgroup>
@endforeach
</select>
and that would give you an output like
<select>
<optgroup label="Fruits">
<option value="1">Apple</option>
<option value="2">Banana</option>
</optgroup>
<optgroup label="Vegetables">
<option value="3">Beans</option>
<option value="4">Cabbage</option>
</optgroup>
</select>
EDIT
relationship is easy as understanding english .. actually you've done it already in your category ads ..
CATEGORY MODEL
public function ads()
{
return $this->hasMany('App\Ad');
// return $this->hasMany('App\Ad','theforeignfieldtocomparetomyprimarykey')
}
hasMany
- this means Ad model has category_id
in it's database table as field ..
in your AD MODEL
public function category()
{
return $this->belongsTo('App\Category');
// return $this->belongsTo('App\Category','myfieldtocompare');
}
belongsTo
- since the function name is category
it will look up on his fields for category_id
and match it to the primary key
of model category
so basically what you have to do is first make models with migrations like:
CATEGORY
SUB CATEGORY
then in your model you should have a script as exampled above ..
Upvotes: 2