Complete website in Rs. 5,000 with Free Hosting & Domain. Offer ends in  00:00:00
Back to Blog

Laravel Tips, Code Snippets and Libraries

Apr 11, 2023 Updated: Apr 11, 2023

Generate Application Key

php artisan key:generate --ansi

Generate Model, Migration, Factory and Resource Controller

Use the singular name for the Model.

Create migration, resource controller, factory, seeder and policy.

php artisan make:model Project -mcrfs --policy

Create for api

php artisan make:model Project -mcrf --api

Model name should be singular.

$user = User::firstOrCreate(
    ['email'=> 'john@test.com'],
    ['name'=> 'John', 'password'=> bcrypt('pass12345')],
);
echo $user->id;

// check but not create in database, just store in variable
$user = User::firstOrNew(
    ['email'=> 'john@test.com'],
    ['name'=> 'John', 'password'=> bcrypt('pass12345')],
);
echo $user->name;

$user = User::updateOrCreate(
    ['email'=> 'john@test.com'],
    ['name'=> 'Brad'],
);
echo $user->id;
$user = User::firstOrCreate(
    ['email'=> 'john@test.com'],
    ['name'=> 'John', 'password'=> bcrypt('pass12345')],
);
echo $user->wasRecentlyCreated ? 'Created' : 'Found';
// return only id and name column
User::all(['id', 'name']);
User::find(9); // find where id is 9
User::find(9, ['id', 'name']); // find where id is 9, return only id and name column
User::findOrFail(9); // find or fail if not found
User::where(['email', 'admin@test.com'])->firstOrFail()
User::where(['email', 'admin@test.com'])->firstOr(function(){
    // custom action if not found
    abort(403);
});
User::findOr(9, function(){
    abort(403);
});
User::whereDate('created_at', '2022-10-27')->first();
User::whereYear('created_at', '2022')->first();
User::whereMonth('created_at', '10')->first();
User::whereDay('created_at', '27')->first();

Route Grouping

Route::middleware(['auth', 'verified'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function(){
        // example.com/admin/profile    route('admin.profile')
        Route::get('profile', [SomeController::class, 'index'])->name('profile');
});

Artisan Commands

Clean Database

  • database The database connection to use
  • drop-views Drop all tables and views
  • drop-types Drop all tables and types (Postgres only)
  • force Force the operation to run when in production
$ php artisan db:wipe {--database=} {--drop-views} {--drop-types} {--force}

Migrate Database

$ php artisan migrate:fresh --seed

Artisan Tinker

Register User

$user = new App\Models\User();
$user->email = 'admin@example.com';
$user->password = Hash::make('password');
$user->type = 'admin';
$user->save();
Contact

Got A Question For Us?

Feel free to ask anything directly on call or fill the form and we will contact back within few hours.