I have Laravel 5.3 and three table there.
Articles table
id
title
body
Systems table
id
title
slug
Sections table
id
title
slug
One article can have/haven't systems or sections (like categories and subcategories). So articles have many-to-many relations with Systems and Sections in pivot tables
article_systems table
id
system_id
article_id
article_sections table
id
section_id
article_id
I am getting in index view all articles with filters by four ways:
- all articles
- all articles with given section
- all articles with given system and any section
- all articles with given system and given section
I use the solution - combine parameters in the ArticlesController and make Query via Scopes.
ArticleController.php
$URI = [];
$URI['system'] = Request::input('system');
if(!$URI['system']){
$URI['system'] = 'all';
};
$URI['section'] = Request::input('section');
if(!$URI['section']){
$URI['section'] = 'all';
};
$articles = Article::Published()
->BySystem($URI['system'])
->BySection($URI['section'])
->paginate(30);
return view('articles.index', compact('articles''URI'));
Article.php Model
public function scopeBySystem($query, $systemRequest){
if($systemRequest && $systemRequest != 'all' ) {
return $query->with('systems')
->whereHas('systems', function ($q) use ($systemRequest) {
$q->where('slug', $systemRequest);
});
}else{
return $query;
}
}
public function scopeBySection($query, $sectionRequest){
if($sectionRequest && $sectionRequest != 'all' ) {
return $query->with('sections')
->whereHas('section', function ($q) use ($sectionRequest) {
$q->where('slug', $sectionRequest);
});
}else{
return $query;
}
}
This code works. But I have my doubts. Is this the best solution that I can do?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire