Support the ongoing development of Laravel.io →
Database Eloquent

I just started using laravel, and I am trying some code.

$candidate1 = ot_Candidate::where('id', '=', '1')->first();
$candidate2 = $candidate1->where('id', '=', '2')->first();
echo $candidate2->id;

When using the code above, the echo actually returns '2'. Shouldn't it be better to throw an error if someone tries this (or setting $candidate2 to null).

Other example:

class ot_Sessions extends Eloquent 
{
    protected $table = 'ot_sessions';
    public $timestamps = false;

    public function Items()
    {
        return $this->hasMany('ot_Items', 'sessionId');
    }

    public function getActiveItem()
    {
        return $this->Items()->where('StatusId', '=', 1)->first();
    }
}

If now someone in a controller uses this code: ot_Sessions::find(1)->getActiveItem()->first(); it gives back an Item, but it will be the first item from all available items in the DB.

I think it is weird that this is allowed, or am i missing something?

Thanks. Kevin

Last updated 3 years ago.
0

Being able to use the activerecord in this way is actually a boon to us. For example:

https://github.com/LaravelIO/laravel.io/blob/master/app/Lio/Core/EloquentRepository.php

Here, we inject a new instance of a model, then use it as a basis for querying against it.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

KevinM86 kevinm86 Joined 3 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.