anonymous-dev
anonymous-dev

Reputation: 3499

How can I use a query of id's for another query with eloquent - Laravel

I am new to back-end development and I am trying to use an intermediary table inside my controller to select the campaigns from user 5. So far I get the following error with the following code. I don't really understand what the error means and the google results are not really helping.

"stripos() expects parameter 1 to be string, object given"

public function index()
{
    $userCampaignIDs = CampaignUser::where('user_id', '5');
    $campaigns = Campaign::findMany('id', $userCampaignIDs);
    return $campaigns;
}

Upvotes: 0

Views: 35

Answers (1)

Vincent Decaux
Vincent Decaux

Reputation: 10714

Because $userCampaignIDs is not an array, but a QueryBuilder.

You have to get an array to use findMany, like this :

$userCampaignIDs = CampaignUser::where('user_id', '5')->get()->pluck('id');

But, you have to use Eloquent relations to get your relations more easily, like :

$userId = 5;
$campaigns = Campaign::whereHas('campaignUser', function($query) use ($userId) {
    $query->where('user_id', $userId);
})->get();

I suppose there is a relation between Campaign and CampaignUser

Upvotes: 1

Related Questions