Answer the question
In order to leave comments, you need to log in
Error with partial duplication?
Good afternoon. Faced such a situation.
There is a table of cars in which there is a brand id and a client id and the name of the car itself. Everything is saved to the database perfectly, but when displaying all this goodness, if 2 lines in the database have the same brand and client id, when trying to get the brand name and client name.
migration
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->unsignedInteger('model_id');
$table->foreign('model_id')->references('id')->on('model')->onDelete('cascade');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
protected $fillable = ['title', 'user_id', 'car_id'];
public function users()
{
return $this->hasMany(User::class, 'id');
}
public function models(){
return $this->hasMany(Model::class, 'id');
}
public function store(Request $request)
{
$car = Car::create([
'title' => $request->title,
'user_id' => $request->user,
'model_id' => $request->publisher
]);
return redirect(route('all_cars'));
}
@foreach($cars as $index => $car)
<tr scope="row">
<td>{{ $index + 1 }}</td>
<td>{{ $car->title }}</td>
<td>{{ $car->models->first()->title }}</td>
<td>{{ $car->users->first()->name }}</td>
</tr>
@endforeach
Answer the question
In order to leave comments, you need to log in
offhand, it seems to me that you made a little mistake with car_id (you have it in fillable) and model_id
and keys in the model
public function users(){
return $this->hasMany('App\User', 'user_id','id');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question