BartHuis
3 years ago
3135
13
Eloquent

make an empty relation

Posted 3 years ago by BartHuis

hi, i would like to make an empty relation, is that possible?

tried

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
        if ($envoirementcheck == TRUE ) {
            return $this->belongsToMany('App\Testrelation');
        } else {
            return null;
        }
        
    }

then i'll get:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

so also tried it this way:

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
        if ($envoirementcheck == TRUE ) {
            return $this->belongsToMany('App\Testrelation');
        } else {
            return New \Illuminate\Database\Eloquent\Relations\Relation;
        }
        
    }

but then i'll get

Cannot instantiate abstract class Illuminate\Database\Eloquent\Relations\Relation

any way to get this done?

and no, i can't just make the relation return nothing, because the envirement check is build in becouse i dont have the related database on certain envoirements. so if i'll just do:

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
            return $this->belongsToMany('App\Testrelation');
       
    }

i'll get:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'envoirementdb.testrelation' doesn't exist

so that's why i don't want the relation to be made in the model when i'm a certain envoirement.

Thanks, Bart

PS: it's possible there's any typo here, just converted our real code into dummy code to show here ;)

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