murilo

WhenWhereHas Eloquent

Posted 1 year ago by murilo

Hello , I have a question .

I want to search Tags ( Many to Many ) in My post , JUST if I select those tags in my search .

I have my code like this -

$tags = $request->input('tags');

Post::select(['id', 'title' , 'description'])
      // TAGS (MANY TO MANY )
            ->WhereHas('Tags' , function($query)  use ($tags ) {
             
                    return $query->where('id' , $tags );
          
            })->latest()->get()

But it dows not have a option if my Tag is empty . I wold like to make something like this -


$tags = $request->input('tags');

Post::select(['id', 'title' , 'description'])
      // TAGS (MANY TO MANY )
        ->when($tags , function ($query) use ($tags ) {
                   ->IfWhereHas('Tags' , function($query)  use ($tags ) {
             
                    return $query->where('id' , $tags );
          })
            })->latest()->get()

  • IfWhereHas or WhenWhereHas , does have this option in Laravel ?

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

Reply to

Use Markdown with GitHub-flavored code blocks.