Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do relationship one to many from one side?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading