Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ncarreno's avatar

Relationship hasMany doesn't work

Hi everyone,

I have a problem with a relationship between two models. I have a model Portfolio:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Portfolio extends Model {

    protected $guarded=[
        'id'
    ];

    public function portfoliotxt() { 
        return $this->hasMany('APP\PortfolioText'); 
    }

}

and I have the PortfolioText model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class PortfolioText extends Model {

    protected $table = 'portfolios_texts';

    protected $guarded=[
        'id'
    ];

    public function portfolio() { 
        return $this->hasOne('APP\Portfolio'); 
    }
}

I can store date in my database but when I try to show data from the relationship Laravel shows me the mesagge:

Class 'APP\PortfolioText' not found

My code to show the data is:

$portfolio->portfoliotxt()->title

I don't know what's wrong but the model Portfolio text is in the app folder. Thanks for your help!

0 likes
3 replies
Fruty's avatar
Fruty
Best Answer
Level 2

Problem with the namespaces declaration in the relations (upper case). You need to change your relations to:


// Portfolio class
public function portfoliotxt() 
{ 
        return $this->hasMany(PortfolioText::class); // or  $this->hasMany('App\PortfolioText');
}


// PortfolioText class
public function portfolio() 
{ 
    // Your relation type must be 'Belongs to', not 'Has one'
    return $this->belongsTo(Portfolio::class);  // or $this->belongsTo('App\Portfolio');
}
1 like
pmall's avatar

First it is hasMany / belongsTo, not hasMany / hasOne.

Then you write 'APP' instead of 'App'. Namespaces are case sensitive.

Finally $portfolio->portfoliotxt() return the relationship object, which has obviously no title attribute. You have to use $postfolio->portfoliotxt so laravel execute the query, and return the collection. By the way it is stored so the next call to $postfolio->portfoliotxt return the collection without executing the query.

One last thing $postfolio->portfoliotxt->title wont work either as portfoliotxt is a collection (has many portfoliotxt), so you have to loop trough your portfoliotxt in order to show their titles.

1 like

Please or to participate in this conversation.