how can i display all posts where animal is dog using laravel

i have 2 tables posts & animals withe a relation of one to may

posts table:
id,
animal_id

animals table:
id,
animal


Animal model:

public function posts()
{
    return $this->hasMany(Post::class);
}

Post model:

public function animale()
{
    return $this->belongsTo(Animal::class);
}

faker:

  public function definition()
{
    return [
        'animal' => $this->faker->randomElement(['Dog', 'cat', 'fish']),

    ];
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’ve got a couple different ways to do this. You can either go via Animal model, or via the Post model:

Via Animal.php model:

$posts = Animal::where('animal', 'Dog')->first()->posts;

Via Post.php model:

$posts = Post::whereHas('animale', function ($query) {
  $query->where('animal', 'Dog');
})->get();

Either of these approaches will return a Collection of Post models that are related to the Animal model for 'Dog'. The approach using animal_id in the other answer is valid, but only if you explicitly know the animals.id for 'Dog' is 1. If that changes, the query is completely invalid.

Method 2

It seems simple you just have to pass the dog id from the animal table.

$dog = Post::where('animal_id',1)->get();

or if you don’t know about ID follow the below approach

$dog = Post::whereHas('animals', function ($query) {
           $query->where('animal', 'Dog');
        })->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x