getting the value of an extra pivot table column laravel

PhpMysqlLaravelMany to-ManyPivot Table

Php Problem Overview


I have a phone_models, phone_problems, and a phone_model_phone_problem pivot table. The pivot table has an extra column 'price'.

PhoneModel:

class PhoneModel extends \Eloquent
{
    public function problems()
    {
        return $this->belongsToMany('RL\Phones\Entities\PhoneProblem')->withPivot('price');
    }
}

PhoneProblem:

class PhoneProblem extends \Eloquent
{
    public function models()
    {
        return $this->belongsToMany('PhoneModel')->withPivot('price');
    }
}

What I'm trying to do is get the price of a specific phone with a specific problem.

This is how I have it now but I feel like Laravel has a built in Eloquent feature I can't find to do this in a much simpler way:

$model = $this->phoneService->getModelFromSlug($model_slug);
$problem = $this->phoneService->getProblemFromSlug($problem_slug);

all this does is select the specific model and problem from their slug.

then what I do is with those credentials I get the price like so:

$row = DB::table('phone_model_phone_problem')
->where('phone_model_id', '=', $model->id)
->where('phone_problem', '=', $problem->id)
->first();

so now I can get the price like so $row->price but I feel like there needs to be a much easier and more 'Laravel' way to do this.

Php Solutions


Solution 1 - Php

When using Many to Many relationships with Eloquent, the resulting model automatically gets a pivot attribute assigned. Through that attribute you're able to access pivot table columns. Although by default there are only the keys in the pivot object. To get your columns in there too, you need to specify them when defining the relationship:

return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Official Docs

If you need more help the task of configuring the relationships with Eloquent, let me know.

Edit

To query the price do this

$model->problems()->where('phone_problem', $problem->id)->first()->pivot->price

Solution 2 - Php

To get data from pivot table:

$price = $model->problems()->findOrFail($problem->id, ['phone_problem'])->pivot->price;

Or if you have many records with different price:

$price = $model->problems()->where('phone_problem', $problem->id)->firstOrFail()->pivot->price;

In addition.

To update data in the pivot you can go NEW WAY:

$model->problems()->sync([$problemId => [ 'price' => $newPrice] ], false); 

Where the 2nd param is set to false meaning that you don't detach all the other related models.

Or, go old way

$model->problems()->updateExistingPivot($problemId, ['price' => $newPrice]);

And remind you:

To delete:

$model->problems()->detach($problemId);

To create new:

$model->problems()->attach($problemId, ['price' => 22]);

It has been tested and proved working in Laravel 5.1 Read more.

Solution 3 - Php

> Laravel 5.8~

If you want to make a custom pivot model, you can do this:

Account.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)
            ->using(AccountUserPivot::class)
            ->withPivot(
                'status',
                'status_updated_at',
                'status_updated_by',
                'role'
            );
    }
}

AccountUserPivot.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class AccountUserPivot extends Pivot
{
    protected $appends = [
        'status_updated_by_nice',
    ];

    public function getStatusUpdatedByNiceAttribute()
    {
        $user = User::find($this->status_updated_by);

        if (!$user) return 'n/a';

        return $user->name;
    }
}

In the above example, Account is your normal model, and you have $account->users which has the account_user join table with standard columns account_id and user_id.

If you make a custom pivot model, you can add attributes and mutators onto the relationship's columns. In the above example, once you make the AccountUserPivot model, you instruct your Account model to use it via ->using(AccountUserPivot::class).

Then you can access everything shown in the other answers here, but you can also access the example attribute via $account->user[0]->pivot->status_updated_by_nice (assuming that status_updated_by is a foreign key to an ID in the users table).

For more docs, see https://laravel.com/docs/5.8/eloquent-relationships (and I recommend press CTRL+F and search for "pivot")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRodrigoView Question on Stackoverflow
Solution 1 - PhplukasgeiterView Answer on Stackoverflow
Solution 2 - PhpYevgeniy AfanasyevView Answer on Stackoverflow
Solution 3 - Phpagm1984View Answer on Stackoverflow