Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Michael Fayez's avatar

How to get data from third model

Hello Best Community :)

Would like to get the assignees people from project when post is created and fire an email to them Here is the Project Model :-

<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;



class Project extends Model
{
   

    public function assignees()
    {
        return $this->belongsToMany(User::class);
    }


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


}

Here is User Model :-

<?php

namespace App\Models;



use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class User extends Authenticatable
{


 

    public function projects()
    {
        return $this->belongsToMany(Project::class);
    }
}

Here is the Post Model :-

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Post extends Model
{
  
  public function project()
    {
        return $this->belongsTo(Project::class);
    }

}

How to get assignees when post is created

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To get the assignees when a post is created, you can use the belongsToMany relationship defined in the Project model. Here's an example of how you can achieve this:

use App\Models\Post;

// Assuming you have the post instance
$post = new Post();

// Get the project associated with the post
$project = $post->project;

// Get the assignees of the project
$assignees = $project->assignees;

// Loop through the assignees and send an email to each of them
foreach ($assignees as $assignee) {
    // Send email to $assignee
}

In this example, we first retrieve the project associated with the post using the project relationship defined in the Post model. Then, we can access the assignees relationship on the project to get the collection of assignees. Finally, we loop through the assignees and perform the desired action, such as sending an email.

Note: Make sure to replace the send email to $assignee comment with your actual email sending logic.

Please or to participate in this conversation.