Laravel Eloquent Relationships Tutorial From Scratch

Admin   PHP   513  2020-08-10 21:21:18

ORM stands for Object-relational mapping. Laravel introduce ORM from Laravel 5 framework version. We used and see the foreign key for database relationship. but in this relation laravel created relationships between model.

As we know database table is almost related to another database table. but when you are working on retrieve data, create data or etc task. you have to use a join or something on every SQL query. So it takes time and also we have to write lots of database query. But in laravel Eloquent Model Relationship we can easily make in relation by using their types.

Why we should use laravel model relationship, So I want to give one example for this. If you have a "users" table and also you have "user_addresses" table. both tables are connected with each other using a foreign key. There are several records in users table and also more records in your address table. If you didn't use laravel eloquent relationship then you can get all address using "join" like as below:

Basic Model Query:

$userAddresses = User::select("users.*", "user_addresses.*")

->join("user_addresses", "user_addresses.id_user", "=", "")

->where("", 1)



As you can above laravel query, you have to write long query, right now it is not big, but when you have more tables connected with users table then it can be more complected, so if we use laravel Relationship then you can do it just simple and you don't require to write every time join and anything, laravel will manage it. So you can write this way:

Model Query Using Relationship:

I hope you found your best tutorials.