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

stretch0's avatar

Getting data with related objects

I am writing a small app which allows a teacher to assign homework to students and then a student able to answer the question / homework as many times as they like.

I am having trouble getting data with related objects.

For example I want to get all answers from the Answer model and each answer to pull in the user info.

My user and Answer models look as such:

User model:

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 {

public function UsersHomework(){
    return $this->belongsTo('models/UsersHomework');
}

public function Answer(){
    return $this->hasMany('models/Answer');
}

use     Authenticatable, CanResetPassword;

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

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

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

}

Answer model:

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model {

    //

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

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

}

Then in my controller I am just calling:

$answers = Answer::all()->toArray();

which is returning:

Array
(
    [0] => Array
        (
            [id] => 1
            [answer] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into 
            [user_id] => 5
            [homework_id] => 1
            [created_at] => 2015-08-24 14:46:29
            [updated_at] => 2015-08-23 02:12:00
            [deleted_at] => 0000-00-00 00:00:00
        )

    [1] => Array
        (
            [id] => 2
            [answer] => electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            [user_id] => 5
            [homework_id] => 2
            [created_at] => 2015-08-24 14:46:30
            [updated_at] => 2015-08-23 02:12:19
            [deleted_at] => 0000-00-00 00:00:00
        )

    [2] => Array
        (
            [id] => 3
            [answer] => Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock
            [user_id] => 5
            [homework_id] => 3
            [created_at] => 2015-08-24 14:46:32
            [updated_at] => 2015-08-23 02:13:30
            [deleted_at] => 0000-00-00 00:00:00
        )

    [3] => Array
        (
            [id] => 4
            [answer] => answer here
            [user_id] => 5
            [homework_id] => 1
            [created_at] => 2015-08-24 14:46:33
            [updated_at] => 2015-08-23 05:51:16
            [deleted_at] => 0000-00-00 00:00:00
        )

)

Are my relationships built correctly? If so, how can I get all user data associated?

0 likes
6 replies
stretch0's avatar

@lancebutler2

I am getting Class 'User' not found.

I have included:

FatalErrorException in Model.php line 824:
use App\models\Homework;

Any ideas?

lancebutler2's avatar

Just a couple suggestions

  1. I'd use camel casing on your functions inside your classes.
  2. Make sure your models are namespaced properly, and you have correct use statements in each model. (You don't HAVE to use use statements if everything is in the same namespace), but I couldn't find your user model, because it's in a different namespace, or some other organizational reason
  3. I tend to use my Use statements regardless, and then reference the class using php 5's ClassName::class (gives you a string representation of the class) convention
  4. I'd have each directory/level of my namespace capitalized.
  5. If you make changes like what I've suggested above, make sure you do a composer dumpautoload afterwards
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\User;
use App\Models\Homework;

class Answer extends Model {

    //

    public function user(){
        return $this->belongsTo(App\Models\User::class);
    }

    public function homework(){
        return $this->belongsTo(App\Models\Homework::class);
    }

}
lancebutler2's avatar
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\User;
use App\Models\Homework;

class Answer extends Model {

    //

    public function user(){
        return $this->belongsTo(User::class); // my bad, I pulled in the User model class above
    }

    public function homework(){
        return $this->belongsTo(Homework::class); // my bad, I pulled in the Homework model class above
    }

}
1 like

Please or to participate in this conversation.