Matt Larsuma
Matt Larsuma

Reputation: 1519

Laravel 5.8 newing up eloquent model and calling accessor in one line?

I have a contact_info_scopes table and one of the scopes is 'Default', which is likely to be the most common scope called, so I'm creating an accessor

public function getDefaultScopeIdAttribute()
{
    return $this::where('contact_info_scope', 'Default')
        ->first()
        ->contact_info_scope_uuid;
}

to get the defaultScopeId and wondering how I can new up the ContactInfoScope model and access that in one line. I know I can new it up:

$contactInfoScope = new ContactInfoScope();

and then access it:

$contactInfoScope->defaultScopeId;

but I would like to do this in one line without having to store the class in a variable. Open to any other creative ways of tackling this as well since an accessor may not really be ideal here! I'd be fine with just creating a public function (not as an accessor), but would have the same issue of calling that in one line. Thanks :)

Upvotes: 0

Views: 194

Answers (2)

MOAZZAM RASOOL
MOAZZAM RASOOL

Reputation: 169

//LARAVEL
//write on model ----------------------------------


protected $appends = ['image']; 

public function getImageAttribute()
    {
        
          $this->school_iMage =   \DB::table('school_profiles')->where('user_id',$this->id)->first();
          $this->studend_iMage =   \DB::table('student_admissions')->where('user_id',$this->id)->first();

        return $this;

    }

//call form anywhere blade and controller just like---------------------------

auth()->user()->image->school_iMage->cover_image;
 or
User::find(1)->image->school_iMage->cover_image; 
 or 
Auth::user()->image->school_iMage->cover_image;

// you can test dd( User::find(1)->image);

Upvotes: 0

ColinMD
ColinMD

Reputation: 964

You should be able to call the model and chain the value if you return the instance in its constructor method

(new ContactInfoScope)->defaultScopeID

Not tried it in Laravel but works in plain ol PHP

Upvotes: 1

Related Questions