PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Cant get proper data in Controller Laravel belongsToMany Relation - Laravel / Eloquent

 March 01, 2022     eloquent, laravel, laravel-5, php     No comments   

Issue

A user(employer) have many posts and many user(employee) can apply these posts . Point is employer should get which users applied for each its posts.

Simply want to get applicants for each posts for each employer id.

I tried $employees = Post::find(//anyNumber//)->people; it gives proper applicants infos but it should be dynamic for each employer user .

Tables..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

Post Model..

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

Controller..

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::find(//anyNumber//)->people; // this line

    dd($employees);
}

Solution

If I understand the question correctly, you are looking for all the employees who applied for the post of the employer. You should be able to pull all those "People" in the same query you get your posts from using the "with" statement.

For example:

$myPosts = Post::where('user_id', $user->id)->with('people')->get();


Answered By - Dan Castanera
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing