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

Mystic's avatar

How to fetch data through relationships between models using api

I am creating a mobile app with react native as the front end and using laravel to create API which I can use to connect with my backend. I am trying to fetch data using relationships between the different models in my database but I keep getting the error (Call to a member function get() on null). Pls anyone have any idea on how I can solve this

0 likes
7 replies
martinbean's avatar

@mystic Well when you get that error, it’ll also have the file and line it occurred. So look there.

Mystic's avatar

Ok here are the codes for the relationship between my user model and mathematics model

User Model

class User extends Authenticatable
{
 
public function mathematics(){
        return $this->hasMany('App\Mathematics');
    }
}

MathematicsController model

use App\User;

use Illuminate\Http\Request;

use App\Mathematics;
class MathematicsController extends Controller
{

 public function teachersUploads($id){
        $maths = User::find($id)->maths;
        return MathResource::collection($maths);
    }

}

Mathematics model

class Mathematics extends Model
{
public function user()
    {
        return $this->belongsTo('App\User');
    }
}

The error I am getting is from this line of code in MathemicsController class

 $maths = User::find($id)->maths;

The error is Call to a member function first() on null in file /opt/lampp/htdocs/schoolApp/vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php on line 24

This is what d code for my Mathematics database

 public function up()
    {
        Schema::create('mathematics', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedBigInteger('user_id')->nullable();
            $table->string('subject')->nullable();
            $table->string('topic')->nullable();
            $table->index('user_id')->nullable();
            $table->text('content')->nullable();

            $table->timestamps();
        });
    }
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You need to use the right name

$maths = User::find($id)->mathematics

But I have a feeling your error is in some code that isn't shown

Mystic's avatar

Thanks so much it helped me in solving the problem...pls i don't know if dis is against the community guideline... i need someone to mentor me in mastering laravel i am a beginner ....I would really love if u can be my mentor

Sinnbeck's avatar

You can always ask people but I think it will be hard to find someone who has the time for such a commitment. Sadly I don't. But feel free to post any questions or problems you run into, on this forum, and I am sure we can help you :)

1 like
Mystic's avatar

Thank you very much for ur sincere response i really appreciate it.

Please or to participate in this conversation.