Home > Enterprise >  Result of an SQL inside the item with $appends
Result of an SQL inside the item with $appends

Time:02-18

I have the following files:

LicensesController.php:

namespace App\Http\Controllers;

use App\Models\License;

class LicencesController
{

    public function showLicense()
    {
        return License::query()
            ->join('plans', 'licenses.plan_id', '=', 'plans.id')
            ->where('licenses.client_id', 1)
            ->get(['plans.id', 'plan_name', 'storage', 'price','expires_at']);
    }
}

Licenses.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class License extends Model
{
    public $timestamps = false;
    protected $appends = ['licenses'];


    public function getLicensesAttribute($licenses): array
    {
        return [
            'total_licenses' => ENTIRE_RESULT_OF_THE_CONSULTATION_HERE,
            'licenses_available' => '123'
        ];
    }
}

How do I, to do the following SQL:

$totalLicenses = License::query()
    ->where('client_id', 1)
    ->get('licenses_quantity');

And with this SQL getting only the integer value of 'licenses_quantity' to populate the 'total_licenses' field in the getLicensesAttribute function?

CodePudding user response:

Total licenses per given client id would be:

$totalLicenses = License::query()
    ->where('client_id', 1)
    ->count();

Tho I'm not sure what you are trying to do with the get attribute.

CodePudding user response:

try something this:

$totalLicenses = License::query()
->where('client_id', 1)->first()->licenses['total_licenses'];
  • Related