Haridarshan Haridarshan - 1 month ago 8
PHP Question

Get data from two relationed Illuminate Eloquent Model in one

currently in one of the project we were using direct sql queries and it is decided to remove them and implement the ORM, so we decided to use Illuminate Eloquent Model component for that. Since we are new to this, I don't have much knowledge with Relations between two Models related to each other.

current sql query

select * from login as A, user_profile as B where A.user_id = B.login_id and A.user_id = $user_id


I've created two Models, one
User
extending
Illuminate\Database\Eloquent\Model
and another
UserProfile
extending
Illuminate\Database\Eloquent\Model
. Model implementation is like this

User Model

<?php
namespace App\Project;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
protected $table = 'login';

protected $primaryKey = 'user_id';

public function profile()
{
return $this->hasOne('App\Project\UserProfile', 'login_id');
}
}


UserProfile Model

<?php
namespace App\Project;

use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model
{
protected $table = 'user_profile';

protected $primaryKey = 'id';

public function user()
{
return $this->belongsTo('App\Project\User', 'user_id');
}
}


I've a class
Manage
with a method
getUserInfo
which takes user_id as input

Manage Class

<?php
namespace App\Project;

class Manage
{
public function getUserInfo($id)
{
return (new User())->profile()->where('login_id', $id)->get();
}
}


When I call this method in the application, I get Empty Collection

Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
)
)


But If I break it in two statements like this

$user = User::find($id);
$profile = $user->profile()->where('login_id', $id)->get();


In
$user
variable I get the Object of
User
Model with data of login table and in
$profile
variable I get the Object of
UserProfile
Model with data of user_profile table. Now I'm not able to understand how can I get the result of two tables in single call using Eloquent Models.

Answer

Ok, got the answer when using where instead of find am able to get single record.

$user = User::where('user_id', $id)->with('profile')->get();
Comments