Patrick Patrick - 28 days ago 19
PHP Question

Get items based on object ID (Laravel)

I am trying to get specific items from the database based on the ID which is referenced on the sub-object.

I have a Shoutout table, and each shoutout consist of multiple Hashtags.
So i have this so far:

public function shoutoutSpecific($hashtag) {
$hashtags = Hashtag::whereHashtag($hashtag)->get();
$shoutouts = '';


return view('shoutout', compact('shoutouts'));
}


But this only gives me the hashtags, where each hashtag references to the specific shoutout. And i need to get the shoutout, which the hashtag is referencing to by ID.

But I was wondering if there is a way to get the shoutouts, where the shoutouts have a specific hashtag referenced to them.
Something like:

Shoutouts = Shoutout::whereHashtag-referenced($hashtag)->get();

Answer

If your Shoutout class has the hasMany relation as:

Shoutout.php

public function hashtags()
{
    return $this->hasMany(App\Hashtag::class);
}

Then you can try as:

Shoutouts = Shoutout::whereHas('hashtags', function($q) use($hashtag) {
    $q->whereHashtag($hashtag);
})->get();