1

why this is not working where all my queries are individually working.

$data = [
    'name' => $user->name,
    'email' => $user->email,
    'phone' => $profile->phone,
    'address' => $profile->address,
    'gender' => $profile->gender,
];

return $data;

this works manually like

$data = [
    'name' => 'my_name',
    'email' => 'my_email',
    'phone' => 'my_phone',
    'address' => 'my_address',
    'gender' => 'my_gender',
];

return $data;

my whole function is given below:

 public function read($id){
        $user=DB::table('users AS t1')
        ->select('t1.name','t1.email')
        ->where('t1.id',$id)->get();

        $profile=DB::table('profiles AS t1')
        ->select('t1.phone','t1.gender','t1.occupation','t1.address')
        ->where('t1.user_id',$id)->get();

        $data = [
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $profile->phone,
            'address' => $profile->address,
            'gender' => $profile->gender,
        ];
       return $data;

1 Answer 1

1

When using get() it returns a collection not a single object so you can do

public function read($id){
        $user=DB::table('users AS t1')
        ->select('t1.name','t1.email')
        ->where('t1.id',$id)->first();

        $profile=DB::table('profiles AS t1')
        ->select('t1.phone','t1.gender','t1.occupation','t1.address')
        ->where('t1.user_id',$id)->first();

        $data = [
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $profile->phone,
            'address' => $profile->address,
            'gender' => $profile->gender,
        ];
       return $data;

Or if you have relations defined on the models you can use the relation

class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


public function read($id)
{
    $user = User::with('profile')->findOrFail($id);

    $data = [
        'name' => $user->name,
        'email' => $user->email,
        'phone' => $user->profile->phone,
        'address' => $user->profile->address,
        'gender' => $user->profile->gender
    ];

    return $data;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@MunnaKhandakar Have updated the answer to show how to use relationship if defined. You may mark the answer as accepted for the benefit of subsequent visitors
thank you very much..... the updated answer is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.