Blog Detail

21

Dec
Top 10 Tips & Tricks You Must Know About Laravel Framework cover image

arrow_back Top 10 Tips & Tricks You Must Know About Laravel Framework

Laravel is a web application development framework with expressive and elegant syntax that makes the whole web development process swift, easier, and pleasant for developers by eliminating all the pain points associated with handling complex PHP code. There are several PHP frameworks available in the market for developing rich web applications like Symfony, Yii, Codeigniter, Phalcon, and many others. But, Laravel has maintained the first position in the list of best MVC-based PHP frameworks due to the comfort and flexibility it delivers to web developers.

So in this blog, I’ve collected some awesome tips and tricks that can help you upgrade your Laravel web development process.

1. HTTP client request without verifying

Sometimes, you may want to send HTTP requests without verifying SSL in your local environment, you can do like so:

return Http::withoutVerifying()->post('https://example.com');

If you want to set multiple options, you can use withOptions.

return Http::withOptions([
    'verify' => false,
    'allow_redirects' => true
])->post('https://example.com');

2. Laravel Request exists() vs has()

// https://example.com?popular
$request->exists('popular') // true
$request->has('popular') // false 

// https://example.com?popular=foo
$request->exists('popular') // true
$request->has('popular') // true

3. Request: has any

You can check not only one parameter with $request->has() method, but also check for multiple parameters present, with $request->hasAny() :

public function store(Request $request) 
{
    if ($request->hasAny(['api_key', 'token'])) {
        echo 'We have API key passed';
    } else {
        echo 'No authorization parameter';
    }
}

4. Add Parameters to Pagination Links

In default Pagination links, you can pass additional parameters, preserve the original query string, or even point to a specific #xxxxx anchor.

{{ $users->appends(['sort' => 'votes'])->links() }}

{{ $users->withQueryString()->links() }}

5. More convenient DD

Instead of doing dd($result) you can put ->dd() as a method directly at the end of your Eloquent sentence, or any Collection.

// Instead of
$users = User::where('name', 'Taylor')->get();
dd($users);

// Do this
$users = User::where('name', 'Taylor')->get()->dd();

6. Using factories with relationships

When using factories with relationships, Laravel also provides magic methods.

// magic factory relationship methods
User::factory()->hasPosts(3)->create();

// instead of
User::factory()->has(Post::factory()->count(3))->create();

7. Preview Mail without Mailable

You can also preview your email without Mailables. For instance, when you are creating a notification, you can specify the markdown that may be used for your mail notification.

use Illuminate\Notifications\Messages\MailMessage;

Route::get('/mailable', function () {
    $invoice = App\Invoice::find(1);
    return (new MailMessage)->markdown('emails.invoice-paid', compact('invoice'));
});

You may also use other methods provided by MailMessage objects such as view and others.

8. Override Permissions for Super Admin

If you’ve defined your Gates but want to override all permissions for SUPER ADMIN user, to give that superadmin ALL permissions, you can intercept gates with Gate::before() statement, in AuthServiceProvider.php file.

// Intercept any Gate and check if it's super admin
Gate::before(function($user, $ability) {
    if ($user->is_super_admin == 1) {
        return true;
    }
});

// Or if you use some permissions package...
Gate::before(function($user, $ability) {
    if ($user->hasPermission('root')) {
        return true;
    }
});

9. Fill a column automatically while you persist data to the database

If you want to fill a column automatically while you persist data to the database (e.g: slug) use Model Observer instead of hard code it every time

use Illuminate\Support\Str;

class Article extends Model
{
    ...
    protected static function boot()
    {
        parent:boot();
        
        static::saving(function ($model) {
            $model->slug = Str::slug($model->title);
        });
    }
}

10. Order by Pivot Fields

BelongsToMany::orderByPivot() allows you to directly sort the results of a BelongsToMany relationship query.

class Tag extends Model
{
    public $table = 'tags';
}

class Post extends Model
{
    public $table = 'posts';

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id')
            ->using(PostTagPivot::class)
            ->withTimestamps()
            ->withPivot('flag');
    }
}

class PostTagPivot extends Pivot
{
    protected $table = 'post_tag';
}

// Somewhere in the Controller
public function getPostTags($id)
{
    return Post::findOrFail($id)->tags()->orderByPivot('flag', 'desc')->get();
}

Note

I hope that by following these tips & tricks you can improve your code quality & performance and enhance your coding journey. If you are a business and want to leverage Laravel for your next PHP-based website development or web application development for your bespoke requirements, you must discover an impeccable team with proficiency in the Laravel framework. So Codebrisk is here to help you with your tailored requirements regarding Laravel Development.

Have an awesome idea? Please feel free to send us an email at rizwan@codebrisk.com or get in touch with us, our business person will get back to you.

Published at : 21-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project