mardi 24 novembre 2015

Laravel 5.1 eloquent relations model- how to update foreign key column?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire