Adding subcategories to laravel 5.4


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)?


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> <blockquote>

and that would give you an output like


<pre class="snippet-code-html lang-html prettyprint-override"><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>


relationship is easy as understanding english .. actually you've done it already in your category ads ..

<strong>CATEGORY MODEL</strong>

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 <strong>AD MODEL</strong>

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:


<ul><li>id</li> <li>name</li> </ul>

<strong>SUB CATEGORY</strong>

<ul><li>id</li> <li>category_id</li> <li>name</li> </ul>

then in your model you should have a script as exampled above ..


  • PostgreSQL: update with left outer self join ignored
  • NoReverseMatch at / Reverse error with urlresolvers, get_absolute_url()
  • Why won't this override of the Model.save() function in Django work?
  • Django implementation of default value in database
  • insert into a MySQL database on a different server
  • Mongodb $addToSet of nested object
  • Source file (.py) not compiling (.pyc not updated)
  • Grouping observations based on first row value
  • How to find the start and end date of a previous month in PHP [duplicate]
  • Entity Framework Core 1.0.1 add-migration
  • Scrolling News Ticker Jquery - Issues
  • Slowly changing dimension - What is Pure type 6 implementation
  • SQL append distinct values from two columns and two tables
  • Hibernate: Inheritance and relationship mapping + generics
  • Using extern @class in order to add a category?
  • “A GKScore must specify a leaderboard.”
  • Type safe keys with Entity Framework model
  • Nested projects in multiproject visual studio templates
  • Should I use composite primary keys in Grails?
  • Tap to record like in vine using javacv
  • Retaining data after updating application
  • Examples of how to a STS in .Net 4.5 using WCF
  • ActiveRecord query for a count of new users by day
  • AT Commands to Send SMS not working in Windows 8.1
  • Comma separated Values
  • How to delete a row from a dynamic generate table using jquery?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • json Serialization in asp
  • KeystoneJS: Relationships in Admin UI not updating
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Error creating VM instance in Google Compute Engine
  • Free memory of cv::Mat loaded using FileStorage API
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • Memory offsets in inline assembly
  • How to stop GridView from loading again when I press back button?
  • Turn off referential integrity in Derby? is it possible?
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize