Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set default attribute values for a custom pivot table?

I am trying to set default values for my pivot table intermediate attributes.

I would expect the $attributes property to work with Pivot classes the same as it does with Model classes, since Pivot extends Model. However that does not seem to be the case, because the property seems to have no effect and the defaults are never assigned.

class Client_orm extends Model 
{
    public function ranks()
    {
        return $this->belongsToMany( 'Rank_orm', 'diy_client_rank', 'client_id', 'rank_id' )
                    ->using( 'Client_rank_orm' )
                    ->withPivot( 'thedate', 'notes' );
    }
}

class Rank_orm extends Model 
{
    public function clients() 
    {
        return $this->belongsToMany( 'Client_orm', 'diy_client_rank', 'rank_id', 'client_id' )
                    ->using( 'Client_rank_orm' )
                    ->withPivot( 'thedate', 'notes' );
    }
}

class Client_rank_orm extends Pivot 
{
    protected $attributes = array(
        'thedate' => 'some default value',
        'notes' => 'some default value',
    );
}

I would expect that with this code, any omitted pivot table attributes would automatically be set with the defaults. However, I am getting the following Illuminate\Database\QueryException when the attributes are omitted:

General error: 1364 Field 'thedate' doesn't have a default value

I realize I could alter the SQL structure to accept NULL values or set defaults, but that would be a last resort if there is no other way to set defaults through model definitions.

Any help would be appreciated!

like image 983
ZGuard Avatar asked Jan 29 '26 22:01

ZGuard


1 Answers

Turns out this one still hasn't been implemented. There is a closed proposal for this: https://github.com/laravel/ideas/issues/872

Currently you can only use wherePivot() feature which actually sets default attributes but it's main purpose is filtering, so you still can not set defaults without filtering which is pretty weird as for me. https://github.com/laravel/framework/pull/22867

like image 104
Stalinko Avatar answered Feb 03 '26 10:02

Stalinko