5

im a beginner at laravel. never worked with framework before. i have created a database named 'tabletest'. it has two table. one is user table and other is phone table.user table has two column(id and name). phone table has 3 column(id phone and user_id). what i was trying is, i will take input using form and send the inputs to the database tables. though the names and the phones were saved in different tables properly, the user_id, which is the foreign key column, was not updated. it was always 0. what should i do now?

Migration files are:

user table:

public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

phone table :

public function up()
    {
        Schema::create('phone', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone');
            $table->unsignedInteger('user_id');
            $table->timestamps();
        });
    }

User model :

use App\Model\Phone;
class User extends Model
{
  protected $table = "user";
  protected $fillable = ['name'];

  public function phone(){
    return $this->hasOne(Phone::class);
  }
}

Phone model :

use App\Model\User;
class Phone extends Model
{
    protected $table = "phone";
    protected $fillable = ['phone','user_id'];

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

PhoneController.php

   <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\model\User;
    use App\model\Phone;
    class PhoneController extends Controller
{
     public function store(Request $request)
        {
            User::create([

                'name' => $request->name
                ]);
            Phone::create([
                'phone' => $request->phone
               ]);
        }
}

here is the screenshot of phone table : phone table

Noob Coder
  • 2,816
  • 8
  • 36
  • 61

1 Answers1

3

You never specify what user you are creating the phone number for. Even though you have a foreign key, that only indexes and constrains the user_id column. MySQL can't "read" your php code and assume which user you were creating a phone number for.

There are a few options.

One you can do this:

$user = User::create([
    'name' => $request->input('name')
]);

Phone::create([
    'phone' => $request->phone,
    'user_id' => $user->id
]);

Or another way is:

$user = User::create([
        'name' => $request->input('name')
    ]);

$user->phone()->create([ // this uses the create method on the users phone relationship
    'phone' => 999999999,
]);

Not sure if chaning this is possible as well, but for readability I wouldn't reccomend it (i.e User::create([])->phone()->create([]);)

Pistachio
  • 1,652
  • 1
  • 18
  • 38
  • there is an error on the line `'name' => $request->input('name');` it says fatal error exception in phonecontroller. syntax error, unexpected ';', expecting ']' @pistachio – Noob Coder Nov 24 '15 at 17:53
  • 1
    sorry, drop the `;` separate with `,` `'name' => $request->input('name'),` – Pistachio Nov 24 '15 at 18:32
  • wow it worked :D thank u brother can u please explain me this line `'name' => $request->input('name'),`? coz what i understand is,u r taking the name attribute from the Form and putting it into $user object.& then u r using `'user_id'=>$user->id;` to assign the user_id value from the $user object. then why do i need to specify these lines in my models?? `public function user(){ return $this->belongsTo(User::class); }` and `public function phone(){ return $this->hasOne(Phone::class); }` – Noob Coder Nov 24 '15 at 19:51
  • 1
    The `$request` object contains all your HTTP request data, including form data. So when you do `$request->input('name');` you ask for the input field with the name `name`. The methods you ask about `phone()` and `user()` are relationships. A use `hasOne` phone, and a phone `belongsTo` a user. That's a One-to-One relationship. This means you can use that relationship to quickly gain access to a users phone. Say you have a view where you show a users profile. `Name: {{ $user->name }} - Phone: {{ $user->phone->phone }}`. Notice I specify what field I want outputted, else I get the phone object – Pistachio Nov 24 '15 at 20:31
  • wow. u really have good knowledge in laravel. i was about to ask this question. u answered it b4 asking lol :P im using the following code to retrieve data from both tables `$alluser=User::with('phone')->get(); return view('index',compact('alluser'));` what if i have another table called address table.. now what should i write to put all these datas inside $alluser? `$alluser=User::with('phone')::with('address')`? @pistachio – Noob Coder Nov 24 '15 at 21:24
  • 1
    `$users = User::with('phone', 'address')->get();` http://laravel.com/docs/5.1/eloquent-relationships#eager-loading – Pistachio Nov 24 '15 at 21:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96092/discussion-between-md-tawsif-ul-karim-tawsif-and-pistachio). – Noob Coder Nov 25 '15 at 01:03