0

I am confuse to use belongstomany in laravel. following is my code.

users.php

public function guser()
{
    return $this-
>belongsToMany(User::class,'reportings','user_id','reporting');
}

SQL TABLEs

REPORTING TABLE:

 ID          USER_ID             REPORTING 
 ==========================================
 1            92                   95,96

USER TABLE:

 ID          NAME
 ================
 92          Sanjay
 95          Ankur
 96          Parkar

result:

Name                 Reporting Person
======================================
Sanjay                Ankur

result expected:

Name                 Reporting Person
======================================
Sanjay                Ankur & Parkar

can you guys please help me to get expected result.

Muhammad Kazim
  • 611
  • 2
  • 11
  • 26
  • how do you store these multiple values(95,96) in your table? – robbyrr Nov 27 '17 at 18:38
  • $inp = Input::get('multireporting'); $values = implode(",",$inp); for ($i = 0; $i < count($inp); $i++) { $news = new Reporting(); $news->user_id = $user->id; $news->reporting = $values; $news->save(); } – Muhammad Kazim Nov 27 '17 at 19:03

1 Answers1

-1

I believe belongsToMany requires a pivot table(would also be best practice to store single values in your database) so why not go that route?

Anyway you could do something like this:

User model:

public function reportings()
{
    return $this->hasMany(Reporting::class);
}

And this function for grabbing the users:

public function getReporters()
{
    //This is just to grab a user, you will probably do it dynamically
    $user = User::find(92);

    $reportings = $user->reportings()->get();

    foreach ($reportings as $reporter) {
        $arr = explode(',', $reporter->reporting);

        for($i = 0; $i < count($arr); $i++) {

            $reporters[] = User::find($arr[$i]);

        }
        foreach ($reporters as $reporter) {
            //just for demo purpose
            echo $reporter->name . ' ';
        }
    }
}

Code could benefit from some serious refactoring but you get the idea.

robbyrr
  • 373
  • 2
  • 7