Home > Software engineering >  Return result from pivot table
Return result from pivot table

Time:07-23

I have multiple campaigns, that can be assigned to multiple users. Basically, they have belongsToMany relation both ways.

I would like to print out the results on the page, that only belongs to that specific user, based on the pivot table.

Models:

User model:

public function campaign()
{
    return $this->belongsToMany(Campaign::class, 'campaign_user');
}

Campaign model:

public function users()
{
    return $this->belongsToMany(Gift::class, 'campaign_user');
}

Migration of pivot table:

public function up()
{
    Schema::create('campaign_user', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->onDelete('cascade');;
        $table->foreignId('campaign_id')->constrained()->onDelete('cascade');
    });
}

Incorrect Controller:

public function index(Request $request)
{
    $data = Campaign::withCount('gifts');
    $data->where('user_id', $request->user()->id)->get();
    return view('subscribes.index', ['data' => $data]);
}

Basically, all I need, is to return specific campaigns, that the client has subscribed only, based on the pivot table/user id. Thus, editing this Controller.

I still face lots of issues with Eloquent models and pivot tables, and I would be very thankful, for any assistance in regards to it.

CodePudding user response:

This will make more sense if you rename the relationship campaign() to it's plural campaigns() on your User model.

Once you have the relationships set up, you can access campaigns for the user straight from the user object.

$user = $request->user();
$data = $user->campaigns;

Note also, if your user is authenticated, you can access them easily like:

$user = auth()->user();

So your index method in your controller would be

public function index(Request $request)
    {
        $user = $request->user();
        $data = $user->campaigns;
        return view('subscribes.index', ['data' => $data]);
    }

  • Related