1

Applogise for image! I did datatable structure like this image. How to get Users data from City side. I used laravel. enter image description here

Newbi
  • 43
  • 5
  • Does this answer your question? [Difference Between One-to-Many, Many-to-One and Many-to-Many?](https://stackoverflow.com/questions/3113885/difference-between-one-to-many-many-to-one-and-many-to-many) – matiaslauriti Mar 29 '23 at 12:13

1 Answers1

1

You have to define a One to Many relationship.

In the City model define a function that return a hasMany relation.

public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

In the User model define the inverse of this function

public function city(): BelongsTo
{
    return $this->belongsTo(City::class);
}

Don't forget to import

Illuminate\Database\Eloquent\Relations\BelongsTo;
Illuminate\Database\Eloquent\Relations\HasMany;

classes.

After that you are free to use this functions ex:

 $users = $city->users() //$city is an instance of City:class

Also read the documentation for more information: Laravel Eloquent Relationships Docs

Telexx
  • 420
  • 2
  • 11