Skip to content
Advertisement

Laravel | Why is the id missing in a eloquent model?

We are customizing our key to use a unique identifier in our routing.

So this

http://127.0.0.1:8000/TEAMS/1

ends up like this

http://127.0.0.1:8000/TEAMS/91e11f44-2d89-4b5e-83e0-5cb92d0c0ebd

This works great but unfortunately we’re getting an error at another point. When we create a new team, we can’t access the id of that newly created team:

dd

You see that the primaryKey points at the id-attribute but this is missing in the attributes-array. So we can’t access

$newTeam->id 
// or
$newTeam['id']

Currently we are fetching the team after creation with

$team = Team::where('identifier', $newTeam->identifier)->first();

but that seems to be redundant.

Does someone know how to resolve this? Thanks in advance.

Edit

This is the relevant part from the model

class Team extends JetstreamTeam
{
    use AppHttpTraitsUsesIdentifier;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'identifier',
        'name',
        'personal_team',
    ];


    /**
     * Specify the routing key
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'identifier';
    }
}

Migration:

class CreateTeamsTable extends Migration
{
    public function up()
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->index();
            $table->string('name');
            $table->boolean('personal_team');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('teams');
    }
}

Trait:

trait UsesIdentifier
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->identifier = (string) Str::uuid();
        });
    }

    public function getIncrementing()
    {
        return false;
    }

    public function getKeyType()
    {
        return 'string';
    }
}

Advertisement

Answer

As there are insufficient information about your table’s primary key, I can assume the following.

  • You have mentioned that you are using custom primary key. the identifier column. So, you don’t have the id column in your table. The default find() method works on the id field.

  • To make it work with your customized identifier column, you have to define the primary key as below.

class User extends Model
{
    protected $primaryKey = 'identifier';
}

After this, you can access model like this:

$team = Team::find($newTeam->identifier);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement