Wednesday, November 24, 2021

Some Examples in Laravel Model



1. get List of years:


    public function getYearList(){
        $years = Application::select('year')->distinct()->orderBy('year')->get();
        $yearList = [];
        if(!empty($years)){
            foreach($years as $y){
                $yearList[] = ['label'=>$y->year, 'value'=>$y->year];
            }
        }
        return $yearList;
    }

2. Select and return an array:

public function getEmailTemplates(){
        return NotificationTemplate::where('status', 'active')->where('trigger_status', '<>', 'Submitted')->get()->toArray();
    }


3.Delete a row:

    public function delLogByAppId($appId){
        FundingLog::where('application_id', $appId)->delete();
    }

4. Use when and with

 Application::with(['funding:type'])

In Application model, there is funding function. In Funding model,  there is a column type

Application::with(['funding:type']) to get all the columns in Application model and type from Funding model

class Application extends Model
{
    use HasFactory;

    protected $table = 'funding_application';
    protected $primaryKey = 'application_id';

    function funding(){
        return $this->belongsTo(Funding::class, 'funding_id', 'funding_id');
    }
}

//when $computingId is true

when($computingId, function($query) use ($computingId) {

Full example:

       $applications = Application::with(['funding:type'])
                                    ->when($computingId, function($query) use ($computingId) {
                                            return $query->where('created_by', '=', $computingId);
                                        })
                                    ->when($fundingArr, function($query) use ($fundingArr) {
                                        return $query->whereIn('funding_id', $fundingArr);
                                    })
                                   ->orderBy('created_at', 'desc')
                                    ->get();


No comments:

Post a Comment