Search code examples
phpsqllaravel-5.4relationships

Getting pivot table information within controller Laravel 5.4


my tables: enter image description here

I have the following controller:

public function index($id){
		$user = User::find($id)->group()->id;
		$group = Group::with('files.urls')->findOrFail($user);
		$data ['group'] = $group;
		return view('upload.files', $data);
	}

Basically in $id - i have id of the user. $user variable should get group_id of that user and use that id in findOrFail function to retrieve group information.

Relationships:

class Group extends Model
{
	public function course(){
		return $this->belongsTo('App\Course');
	}
	public function user(){
		return $this->belongsToMany('App\User');
	}
	public function files(){
		return $this->hasMany('App\File');	
	}
}

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'phone'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
    public function group(){
    	$this->belongsToMany('App\Group');
    }
}


Solution

  • Your relationships are ok.

    I think your logic is not well because it's considering just one group for the user, but a user could have many groups.

    You should consider retrieve all groups first then perform the rest of the logic.

    $groups = App\User::find(1)->group()->get()->toArray();
    $groups = array_column($groups, 'group');
    $files = App\Files::select('urls')->whereIn('group_id', $groups);
    

    Edit.

    Your group relationship in the User model doesn't have a return.