Chonchol Mahmud
Chonchol Mahmud

Reputation: 2735

How to joins table in Laravel 5.2?

I have this table in Laravel Framework:

profiles table:

enter image description here

I want to fill up userID column when any user creates a profile. For this I am trying to code something like this:

Profile model:

public function users()
{
    return $this->belongsTo('App\User','userID');
}

And User model:

public function profiles()
{
    return $this->hasMany('App\Profile');
}

In this way it keeps null value every time. How can I solve this?

Upvotes: 1

Views: 168

Answers (2)

Siddharth
Siddharth

Reputation: 1769

While inserting Data into Profile Table, you just need to do as follows:

$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();

There is no need to join the tables for inserting the value in Profile Table for here. Hope this helps you

Upvotes: 1

Laracademy
Laracademy

Reputation: 148

So assuming you have the following (which you kind of do)

public function profiles()
{
  return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}

<?php
// Profile.php (Model)

public function user()
{
  $this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}

You have a few options, you can either when creating the profile, assign the user_id (as long as it is in the fillable fields.

$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();

Or since we have a relationship you should be able to do something like this

$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.

Hopefully that sheds some light

Upvotes: 2

Related Questions