Skip to content

Instantly share code, notes, and snippets.

@abdulwahhabkhan
Last active February 15, 2025 22:32
Show Gist options
  • Save abdulwahhabkhan/bfa995fdffe4406f729e00f810b52456 to your computer and use it in GitHub Desktop.
Save abdulwahhabkhan/bfa995fdffe4406f729e00f810b52456 to your computer and use it in GitHub Desktop.
Setup laravel application like a PRO

These changes will make your application awesome.

Models

Change base model extend

Chage the model stub so that common functionality can be added to all model, same as controller.

Strict mode

All unsed properties, morphs without mapping, lazy loading will be disabled on local.

Immutable Dates

Dates will be immutable default and you are free to update and use without worring about the inconsistancy in data.

Test

Freeze Time

This will freeze the time for test and checking date time during the test execution at different stages will bring the consistant results. I found is very usefull while testing for file name contain date and time.

Resources

https://www.youtube.com/watch?v=DR1o-u2AFPA&t=7305s

<?php
namespace App\Providers;
use App\Models\User;
use Carbon\CarbonImmutable;
use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\HtmlString;
use Illuminate\Support\ServiceProvider;
use URL;
class CustomServiceProvider extends ServiceProvider
{
public function register(): void {}
public function boot(): void
{
$this->configureCommands();
$this->configureUrls();
$this->configureDates();
$this->configureModels();
}
private function configureDates(): void
{
Date::use(CarbonImmutable::class);
Carbon::macro('displayDate',
fn () => new HtmlString($this->format('M j<\s\u\p>S</\s\u\p> Y')));
Carbon::macro('inputDate',
fn () => $this->format('d M Y'));
}
private function configureModels(): void
{
Model::unguard();
Model::shouldBeStrict(! app()->isProduction());
Relation::enforceMorphMap([
'users' => User::class,
]);
}
private function configureCommands(): void
{
DB::prohibitDestructiveCommands(app()->isProduction());
}
private function configureUrls(): void
{
if (app()->isProduction()) {
URL::forceScheme('https');
}
}
}
<?php
namespace App\Models;
class Model extends \Illuminate\Database\Eloquent\Model
{
public static function table(): string
{
return (new static)->getTable();
}
public static function column($name): string
{
return (new static)->getTable().'.'.$name;
}
}
<?php
namespace {{ namespace }};
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Model;
class {{ class }} extends Model
{
use HasFactory;
protected $guarded = [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment