Master Laravel: 7 Essential Tips for Clean Code and Efficient Performance
This article walks through seven practical Laravel techniques—including view composers for reusable sidebars, route naming for maintainable URLs, dynamic key‑value settings, concise database query shortcuts, polymorphic relationships, caching best practices, and separating Redis connections—to help developers write cleaner, more scalable backend code.
1. Reusable Sidebar with View Composers
Instead of loading sidebar data in every view, create a widgets folder and bind data to the sidebar using a Laravel ViewComposer. This decouples data fetching from the view and allows the sidebar to be included anywhere.
<div class="widget widget-default">
<div class="widget-header">
<h6><i class="fa fa-folder fa-fw"></i>分类</h6>
</div>
<ul class="widget-body list-group">
@forelse($categories as $category)
@if(str_contains(urldecode(request()->getPathInfo()), 'category/'.$category->name))
<li class="list-group-item active">
{{ $category->name }}
<span class="badge">{{ $category->posts_count }}</span>
</li>
@else
<a href="{{ route('category.show', $category->name) }}" class="list-group-item">
{{ $category->name }}
<span class="badge">{{ $category->posts_count }}</span>
</a>
@endif
@empty
<p class="meta-item center-block">No categories.</p>
@endforelse
</ul>
</div>Place the Blade file under resources/views/widgets/categories.blade.php.
<?php
namespace App\Http\ViewComposers;
use App\Http\Repositories\CategoryRepository;
use Illuminate\View\View;
class CategoriesComposer
{
protected $categoryRepository;
public function __construct(CategoryRepository $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function compose(View $view)
{
$categories = $this->categoryRepository->getAll()
->reject(function ($category) {
return $category->posts_count == 0;
});
$view->with('categories', $categories);
}
}Register the composer in a service provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
View::composer('widget.categories', 'App\Http\ViewComposers\CategoriesComposer');
}
public function register()
{
//
}
}Finally, add the provider to config/app.php:
'providers' => [
// ...
App\Providers\ComposerServiceProvider::class,
],Now the sidebar can be included anywhere with @include('widget.categories').
2. Use Route Aliases
Give each route a stable name so URL changes do not require editing every view.
Route::get('user/profile', 'UserController@showProfile')->name('user.profile');In Blade templates use {{ route('user.profile') }} instead of hard‑coded paths.
3. Global Dynamic Settings via a Key‑Value Table
Create a simple maps table to store arbitrary settings.
$table->text('value')->nullable(true);Insert rows with a tag (e.g., settings) and a value. Retrieve them in a composer and bind to views, allowing runtime changes to site title, background, comment toggles, etc., without code modifications.
<?php
namespace App\Http\ViewComposers;
use App\Models\Map;
use Illuminate\View\View;
class SettingsComposer
{
public function compose(View $view)
{
$settings = Map::where('tag', 'settings')->get();
$view->with('settings', $settings);
}
}4. Concise Database Queries
Count related comments efficiently:
$post = Post::where('id', 1)
->withCount('comments')
->first();
$commentsCount = $post->comments_count;Filter counted comments, e.g., only those with more than 100 likes:
$post = Post::where('id', 1)
->withCount(['comments' => function ($query) {
$query->where('like', '>', 100);
}])
->first();5. Polymorphic Relationships
Allow multiple models (posts, pages, etc.) to share a single comments table.
// Comment model
public function commentable()
{
return $this->morphTo();
}
// Any model that can be commented
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}Saving a comment without knowing its parent type:
$comment = new Comment;
$commentableId = $request->get('commentable_id');
$commentable = app($request->get('commentable_type'))
->where('id', $commentableId)
->firstOrFail();
$commentable->comments()->save($comment);6. Caching Best Practices
Never call env() outside configuration files; use config() after running php artisan config:cache. Also avoid closures in route files so php artisan route:cache can work.
7. Separate Redis Connections for Cache, Session, and Queue
Define distinct Redis databases to prevent clearing one from affecting the others.
'redis' => [
'cluster' => false,
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
'session' => [
'database' => 1,
],
'queue' => [
'database' => 2,
],
],Configure the corresponding connection options in config/queue.php and config/session.php so each service uses its own Redis DB.
These seven tips illustrate how Laravel’s expressive API can be leveraged for modular, maintainable, and high‑performance backend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
