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 :
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([]);
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With