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'=> ''],
    ['name'=> 'John', 'password'=> bcrypt('pass12345')],
echo $user->id;

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

$user = User::updateOrCreate(
    ['email'=> ''],
    ['name'=> 'Brad'],
echo $user->id;
$user = User::firstOrCreate(
    ['email'=> ''],
    ['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', ''])->firstOrFail()
User::where(['email', ''])->firstOr(function(){
    // custom action if not found
User::findOr(9, function(){
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'])
        //    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 = '';
$user->password = Hash::make('password');
$user->type = 'admin';

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.