spoon
1244
5
Eloquent

Model class not found (Beginner question)

Posted 3 years ago by spoon

Hi!

I created a relationship and I must say that it was easy, but I got stuck here.

Here's my current setup. I created a relationship between user and album. (One user may have one more than album)

routes.php

<?php
use App\Models\Album;

Route::get('album', function() {
    $albums = Album::all();
    return view('album')->with('albums',$albums);
});

User.php

<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';
    protected $primaryKey = 'user_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['username', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function album() {
        return $this->hasMany('Album');
    }

}

Album.php (it's in the Models folders. I created Models folder to keep my app organized)

<?php
namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Album extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'album';
    protected $primaryKey = 'album_id';

    protected $fillable = ['name', 'created', 'updated', 'user_id'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */

    public function user() {
        return $this->belongsTo('User');
    }

}

If I change return $this->belongsTo('User'); to return $this->belongsTo('\App\Models\User');, it works. How can I make it work without adding \App\Models at the beginning of the User?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.