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:

animals table:

Animal model:

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

Post model:

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


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



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');

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 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');

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

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x