Ali Erfani
Ali Erfani

Reputation: 692

Laravel 5.1 How to map an array of ids onto their corresponding values in another table?

I have a table column which holds an array of subject ids selected by the user. There is another table for these subjects and their values. I need to return the values corresponding to the ids saved in the subjects column. To make it more clear suppose that a user have chosen 5 subjects out of 34 subjects and the corresponding ids are saved in the subjects column as a string like this: 2,5,11,21,23 Each of these numbers corresponds to the id of a subject in the subjects table.

    //This is the subjects table
public function up()
    {
        Schema::create('subjects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('subject', 20);
            $table->timestamps();
        });
    }
//and this is the user_info table
 public function up()
    {
        Schema::create('user_info', function (Blueprint $table) {
    ...
    $table->string('subjects');
    ...
     });
    }

How can I return an array of subject values to a view?

Upvotes: 0

Views: 900

Answers (2)

Ali Erfani
Ali Erfani

Reputation: 692

After some searching around I found that maybe the best solution for my problem was to use the Many to Many relationship. So I removed the subjectscolumn from user_info table. Then I created the pivot table subject_user to save the id of user and their subjects ids in this table. This is the pivot table schema:

Schema::create('subject_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->index();
            $table->integer('subject_id')->index();
            $table->timestamps();
        });

Then in the User and Subject models I established the proper many to many relationship as follows:

//User Model
 public function subjects()
    {
        return $this->belongsToMany('App\Subject')->withTimestamps();
    }
//Subject Model
 public function users()
    {
        return $this->belongsToMany('App\User');
    }

Finally in the controller i used the attach() and sync() methods to populate or update the pivot table.

//In store method
        $user->subjects()->attach($subjects);
//In update method
        $user->subjects()->sync($subjects);

The difference between attach and syn is described here.

Upvotes: 0

Amo
Amo

Reputation: 2944

// Find whichever user
$user = \App\User::find(1);

// Convert the string of subjects from a string to an array
$subjectIds = explode(',', $user->subjects);

// Load all subjects which match the ids within the subjectIds array
$subjects = \App\Subjects::whereIn($subjectIds)->get();

// Do something with the subjects
foreach($subjects as $subject) {
   // Output the subject name 
   var_dump($subject->name);
}

Upvotes: 2

Related Questions