Home > Software engineering >  Laravel, display data where all Ids are matched
Laravel, display data where all Ids are matched

Time:05-19

In controller index function I'm picking up which news ids are matching with a pack id:

$content_pack_news_array = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->get();

Using dd I get this result which I need to access news_id of all elements in it

  Illuminate\Support\Collection {#3017 ▼
  #items: array:2 [▼
    0 => {#2376 ▼
       "news_id": 2
       "content_pack_id": 2
    }
    1 => {#3010 ▼
       "news_id": 4
       "content_pack_id": 2
    }
  ]
}

How to return data that matched with ids:

"news_id": 2
"news_id": 4

Inside:

$news = News::with(['media', 'assigned_content_packs'])->where('id' , $news_id)->get();

If I use

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->first();

It works but it gets only first matching item to display. Any help appreciated.

CodePudding user response:

You can use pluck, to get the ids out.

$newsIds = DB::table('content_pack_news')
    ->where('content_pack_id' , $content_pack_id)
    ->pluck('news_id');

Pluck works great in combination with whereIn(), that checks a column against an array.

$news = News::with(['media', 'assigned_content_packs'])
    ->whereIn('id' , $newsIds)
    ->get();

CodePudding user response:

You can do it in single query using sub query as:

$news = News::with(['media', 'assigned_content_packs'])
                ->whereIn('id', function($query) use($content_pack_id){
                    $query->select('news_id')
                    ->from('content_pack_news')
                    ->where('content_pack_id', $content_pack_id);
                })
            ->get();

CodePudding user response:

if i correct you only asking the first.

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->first();

change it to get(); then you get all records.

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->get();
  • Related