skip to Main Content

Laravel Eloquent: Create custom attribute from subquery

Modal: Subscription.php class Subscription extends Model { use HasFactory; public function payments(): HasMany { return $this->hasMany(SubscriptionPayment::class, 'sub_id'); } public function totalDurationDays(): Attribute { return Attribute::make( get: fn() => $this->payments()->sum('duration_days') )->shouldCache(); } } Controller: SubscriptionController.php $subs = SharedServer::from('subscriptions AS ss') ->select(…

VIEW QUESTION

Laravel Elequent Query Builder on Pivot

I have a three tables post(Model: Post), user(Model: User) and post_user_pivot for votes. The Schema of my pivot table Schema::create('post_user', function (Blueprint $table) { $table->id(); $table->enum('type', ['up', 'down'])->default('up'); $table->unsignedBigInteger('post_id'); $table->unsignedBigInteger('user_id'); $table->timestamps(); }); Storing the votes using attach along with the…

VIEW QUESTION

Laravel – Custom Intermediate Table Models – eager loading

Here is my current setup: <?php namespace AppModels; use Exception; use IlluminateDatabaseEloquentModel; use IlluminateDatabaseEloquentRelationsBelongsTo; use IlluminateDatabaseEloquentRelationsBelongsToMany; class Employee extends Model { protected $table = 'employees'; protected $fillable = [ 'first_name', 'last_name', 'gender', 'birthdate', 'nationality_id', 'company_id', ]; public function positions(): BelongsToMany…

VIEW QUESTION
Back To Top
Search