My favorite tricks in Laravel

05 Dec 2016

1. Use Model as much as possible

It will help you encapsulate your business logic and reuse every where. Learn more about query scope. It will make your code more readable.

<?php

class Ads extends Model
{


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function poster()
    {
        return $this->belongsTo(User::class, 'posted_by');
    }

    /**
     * Scope a query to only include active users.
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', 1);
    }


    /**
     * Set the user's first name.
     *
     * @param  string $value
     * @return void
     */
    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = str_slug($this->title) . '-' . time();
    }

    /**
     * @param $query
     * @param User $user
     * @return mixed
     */
    public function scopeOfUser($query, User $user)
    {
        return $query->where('posted_by', $user->id);
    }
}

2. Unit test

Definitely, it’s good.

3. Don’t use Repository

I used to be a huge fan of this kind of pattern. However I realize that it’s bit over-engineering or my projects still not large enough to implement it. So keep it simple.

4. Don’t use Presenter

Instead of using Presenter, I will Traits then include it into my model. A bit tricky however it gets stuff done.

5. Don’t use the package that break Laravel structure

It’s will be hard to upgrade later.

6. Spend time to upgrade to latest version

The workflow improved version after version, you if you spend time to upgrade, it will reduce a lot of time to accomplish a task. I mean in the workflow.

Tweet me @huynhbathanh if you like this post.

Tweet
comments powered by Disqus