Source: martinjoo.dev

Blog for Laravel Artisans
First, let's discuss what SOLID stands for: Single-responsibility principle It's a set of principles mainly focusing on object-oriented programming made popular by Robert C. Martin.

Fortunately, the fix is pretty easy: class UserResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'full_name' => $this->full_name, 'most_popular_posts' => $this->when( $request->most_popular_posts, $this->mostPopularPosts, ), ]; }} class User extends Posts { public function mostPopularPosts(): Collection { return $this->posts() ->where('like_count', '>', 50) ->where('share_count', '>', 25) ->orderByDesc('visits') ->take(10) ->get(); }}

It looks something like that: trait Likeable { public function like(): Like { } public function dislike(): void { } public function likes(): MorphMany { } public function likeCount(): int { return $this->likes()->count(); }} class Post extends Model { use Likeable; } class Comment extends Model { use Likeable; }

The attribute accessor looks like this: class OrderItem extends Model { public function priceType(): Attribute { return new Attribute( get: fn () => PriceTypes::from( $this->product->price_type )->create($this), ); }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners