Answer the question
In order to leave comments, you need to log in
Laravel Why doesn't a one-to-one relationship work?
Greetings!
Explain why the one-to-many relationship is not working.
In the User model
<?php
namespace App\Models;
use App\Models\Avatar;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $fillable = [
'parent',
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function avatar()
{
return $this->hasOne(Avatar::class);
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Avatar;
use Illuminate\Http\Request;
class RatingController extends Controller
{
public function rating()
{
$user = User::all();
dd($user->avatar);
}
}
Answer the question
In order to leave comments, you need to log in
show your avatar migration
should be like this
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
public function user()
{
return $this->belongsTo(User::class);
}
$user = User::find(1);
$firstUserAvatar = $user->avatar->img;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question