belongsToMany Last updated: 2022-12-13

Let's take a look at the following example to understand how belongsToMany works in Dash

Sometimes you add articles
You need to put a certain article in more than one section
Of course you will use One To Many relationship 

So you only have to do two steps for dash project , in your resource file you can add the following

 belongsToMany()->make('Choose Categories', 'categories',CategoriesResource::class)

Label : Choose Categories 

method : categories in current model Article

reference resource is : App\Http\DashResource\CategoriesResource

According to the processing of your relations with the model

namespace App\Models;

use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model implements TranslatableContract {
	use HasFactory, SoftDeletes, Translatable;
	public $translatedAttributes = ['name', 'content'];

	protected $fillable = [
		'id',
		'image',
	];
 
	public function categories() {
		return $this->belongsToMany(Category::class );
	}

With the table in the database that will store the data article_category

Whether you use multiple languages or not
This is not a problem. Dash will prepare the data according to the language you use in the control panel, with the ability to search if you have many categories

 

 

you can ran other query in the same relation model 

this method works on belongsTo , belongsToMany relationship

example: 

belongsTo()->make('Group', 'admingroup',AdminGroups::class)
     ->query(function ($model) {
     // full_power , owner , moderate 
					return $model::whereIn('admin_type', ['owner', 'moderate']);
				})