nhayder
2 months ago

how to passing dynamic parameters to hasMany relationship

Posted 2 months ago by nhayder

i'm in this situation where i have widget has many articles relationship,

this is my controller

    public function page($slug = null)
    {

        if($slug){

            $id = Page::getPageID($slug);

        }else{
            
            $id = Page::getHomePage();

        } 
            
        $pageWidget = Widget::getPageWidgets($id);

        return view('public.welcome', compact( 'pageWidget'));

    }

this is the getPageWidgets function where i'm loading all articles related to this page

    public static function getPageWidgets($id)
    {
        $pageWidget = Widget::with(

                        'category.selectedsubcategory.articles',

                    )

                    ->where('page_id', '=', $id)

                    ->get();

        return $pageWidget;
    }

// this is the article relationship that loads the articles,

    public function articles()
    {
        return $this->hasMany(Article::class, 'id', 'contentcategory') 

            ->where('language', '=', 'en') // <---- the article local should be dynamic

            ->orderBy('id', 'desc')

            ->take(12);

    }

i need to load articles according to page language, The relationship above will load en articles only.

so how can pass parameters like en,fr,de, ... to the article relationship above.

any ideas.

Please sign in or create an account to participate in this conversation.