K
K
kullx2021-04-15 17:55:06
Laravel
kullx, 2021-04-15 17:55:06

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);
    }
}


The avatars table has a user_id column on which data should be pulled.

When trying to display the user's avatar
<?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);
     }
}


Throws an error: Property [avatar] does not exist on this collection instance.
What is it connected with?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zordec, 2021-04-15
@zordec

show your avatar migration
should be like this

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
          ->references('id')->on('users')
          ->onDelete('cascade');

This method in avatar model
public function user()
    {
        return $this->belongsTo(User::class);
    }

To get avatar in controller
$user = User::find(1);
$firstUserAvatar = $user->avatar->img;

Well, it seems like something like this should work, you need to try it.

V
Vladislav, 2021-04-16
@vos_50

And who will write the link in the request for you?->with('avatar')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question