belongToMany Example

PHOTO EMBED

Fri Jan 10 2025 15:10:54 GMT+0000 (Coordinated Universal Time)

Saved by @dustbuster #php #laravel

 public function states()
  {
      return $this->belongsToMany(
          State::class, // Related model
          'user_state', // Pivot table name
          'user_id', // Foreign key on the pivot table (points to User)
          'state_abbrev', // Foreign key on the pivot table (points to State)
          'id', // Local key on the User model
          'state_abbrev' // Local key on the State model
      )->withPivot('state_abbrev'); // include any info from the pivot table
  }
content_copyCOPY

This is connecting user with states via user_authrzd_state_acs table