I have 3 databases like theses :
formations subjects formation_subject
| id | name| | id | name | is_optional | | formation_id | subject_id |
___________ _________________________ ____________________________
where in the Models\Subject,
public function formations()
{
return $this->belongsToMany(Formation::class);
}
and in the Models\Formation,
public function formationsSubjects()
{
return $this->belongsToMany(Subject::class);
}
in my controller, I have :
$formations = Formation::get()->pluck('name','id);
$options = Subject::where('is_optional', 1)->get();
On my blade, I have a dropdown of $formations, and whenever the selected option of that dropdown is changed, I'd like to get a list of dropdown of $options, which are the Subject are optional ('is_optional' == 1) and the Subject belongsTo(Many) the previously selected $formations
I've tried like this,
$options = Subject::where('is_optional',1)->whereIn('id', function($query) use ($formations){
$query->select('formation_id')
->from('formation_subject')->whereIn('formation_id',$formations);
})->get()->pluck('code', 'id');
But the results didn't matched with what's supposed to appear, and stay the same no matter the formations dropdown is selected.
CodePudding user response:
Laravel has a very thorough documentation I suggest that you study the basics of Laravel and/or reading the documentation: https://laravel.com/docs/9.x
To answer your question, you can use the eloquent whereHas
method: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
And I think this is the code that want:
$formationIds = Formation::whereHas('formationsSubjects', function (Builder $query) {
$query->where('is_optional', 1);
})->get()->pluck('id');
CodePudding user response:
Laravel is on the backend, and whatever is in Blade file is just HTML that is send to the client (front-end)
If you want to do something in one field and the DATA get changed, to must get that data from the backend, either from an AJAX request, or re-render the whole page. AJAX request is of course prefered
You can write Javascript to do AJAX request yourself, or you may want something automatic, look for livewire