Laravel Code Snippets

Laravel development is all about writing code that is both efficient and elegant. In order to achieve this, it helps to have a strong understanding of the Laravel framework itself, as well as the best practices that are commonly used within the Laravel community.

Do you ever find yourself looking for a piece of code to help with a certain task, but can’t seem to find anything that fits the bill? Well, you’re in luck! This curated list of Laravel code snippets will have everything you need to get the job done. From basic routing and controllers to complex database interactions, you’ll be able to find what you need here. So why not take a few minutes and bookmark this page for future reference? You’ll be glad you did!

Laravel Code Snippets

Cache

Clear the Cache on Shared Hosting Servers —
Route::get('/clear-cache', function() {
    $exitCode = Artisan::call('cache:clear');
    echo 'Cache emptied';
});
Route::get('/clear-view', function() {
    $exitCode = Artisan::call('view:clear');
    echo 'View cache emptied';
});

Database

Get Last N Days Records —
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;

class UserController extends Controller
{
   
    public function index()
    {
        $half_month_ago = Carbon::now()->subDays(15);
  
        $sales = User::where('order_date', '>=', $half_month_ago )->get();

    }
}
Get the Latest Inserted Id —
//
$data = new Invoice;
$data->document = 'Invoice/2020/07';
$data->save();
$id = $data->id;

//
$saleId = DB::table('sales')->insertGetId([
    'document' => 'Invoice/2020/07'
]);

//
$order = Order::create(['document' => 'Invoice/2020/07']);
$id = $order->value('id');
Get the Latest Record —
$language = DB::table('languages')->latest()->first();
$language = DB::table('languages')->orderBy('id', 'DESC')->first();

$language = ProgrammingLanguage::latest()->first();
$language = ProgrammingLanguage::select('id')->where('type', $type)->latest('id')->first();
$language = ProgrammingLanguage::orderBy('created_at', 'desc')->first();

$language = ProgrammingLanguage::all()->last();
$type = ProgrammingLanguage::all()->last()->pluck('type');
$latest_id = ProgrammingLanguage::all()->last()->id;
$latest_id = ProgrammingLanguage::orderBy('id', 'desc')->first()->id;
Fix "Specified key was too long error" —
//In AppServiceProvider.php
use Illuminate\Support\Facades\Schema;

public function boot()
{
    //Schema::defaultStringLength(191);
    Schema::defaultStringLength(255);
}

//set max length for each field
$table->string('username', 255);
$table->string('email', 255);
Order Results by Specific Values —
$sales = DB::table('sales')
->orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC")
->get();

$sales = Sale::orderByRaw("FIELD(state , 'SENT', 'DRAFT', 'DONE', 'CANCEL') ASC")
->paginate(100);
Search Data in JSON Field —
//use where
$term = 'Java';
$data = ProgrammingLanguage::where('language', 'like', '"%.$term.%"')->get();

//use json_contains
$keyword = 'Kotlin';
$language = ProgrammingLanguage::whereRaw('json_contains(language, \'["' . $keyword. '"]\')')->get();

//use whereJsonContains in Laravel 5.6+
$flutter = ProgrammingLanguage::whereJsonContains('language', ["Flutter"])->get();
$mobileLanguages = ProgrammingLanguage::whereJsonContains('language', ["Flutter", "React Native"])->get();
Check If Record Is Created or Updated Successful —
//check if record was created succesfully
$message = Message::create($data);
if($message->exists){
	echo 'created';
} else {
	echo 'failed';
}

//check if record was updated succesfully
$affectedRows = Message::where('id', 12)->update(["body" => "Updated body"]);
if($affectedRows > 0){
	echo 'updated';
} else {
	echo 'failed';
}

Datetime

Convert Timestamp into Carbon Datetime —
$datetime = Carbon::createFromTimestamp(-1)->toDateTimeString(); //"1970-01-01 07:29:59"
$datetime = Carbon::createFromTimestamp(1254125678)->toDateTimeString(); //"2009-09-28 16:14:38"
$datetime = Carbon::createFromTimestamp(1654009995)->toDateTimeString(); //""2022-05-31 23:13:15"
$datetime = Carbon::createFromTimestampUTC('1654010143')->format('Y-m-d\TH:i:s.uP'); //"2022-05-31T15:15:43.000000+00:00"
$datetime = Carbon::createFromTimestampUTC('954075600')->format('Y-m-d'); //"2000-03-26"
Add and Subtract Years —
//add years
$now = Carbon::now();
$oneYearLater = $now->addYear(1); 
$fiveYearsLater = $now->addYear(5); 
$tenYearsLater = $now->addYear(10); 

//subtract years
$twoYearsBefore = $now->subYear(1); 
$fiveYearsBefore = $now->subYear(5); 
$oneHundredYearsBefore = $now->subYear(100); 
Change Application's Timezone —
//in config/app.php
/*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */
'timezone' => 'America/Chicago'

Debug & Profiling

Generate Dummy Data —
use Faker\Factory as Faker;

$faker = Faker::create();
DB::table('account')->insert([
    'username' => $faker->userName(),
    'password' => $faker->password(),
    'about' => $faker->sentence(),    
    'created_at' => \Carbon\Carbon::now(),
    'Updated_at' => \Carbon\Carbon::now(),
]);

Email

Create and Send an Email —
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;

use App\Equipment;
use App\Mail;

class EmailController extends Controller
{

    public function sendMail(){
        $details = [
            'title' => 'Due for Review',
            'body' => '<p>There are equipment that needs your atention: </p>'
        ];

        $details['body'] .= '<ul>';
        $dueInspections = Equipment::all();
        foreach($dueInspections as $equipment){
            $details['body'] .= '<li>'.$equipment->name.'<li>';
        }
        $details['body'] .= '</ul>';

        \Mail::to('[email protected]')->send(new \App\Mail\MainMail($details));

        dd($details);
    }


}

Form

Set Default Value for Password Field —
//use Form::input()
{!! Form::input('password', 'email_password', $settings['email_password'], array('class' => 'form-control')) !!}
Use Ajax —
<script type="text/javascript">

$(function() {    
   
    setInterval( function(){ fetchOrders(); }, 30000 );
    function fetchOrders(){        
        $.ajax({
             type: 'GET',
             dataType: "json",
             url: '{{ url("/ajax/order/fetch") }}',
             success : function(results) {    
                
                if(results.success){
                    var orders = results.data;
                    if(orders.length > 0){
                        for(var i = 0; i < orders.length; i++){
                                                                                    
                                                
                        }
                    }
                }
                
             }
        }); 
    }    
});
</script>

Menu & Navigation

Redirect to Previous Page —
return back();
return back()->withInput();
return redirect()->back(); 
Check If Current Page is Home Page —
//in view
{!! Request::is('/') ? '' : url('/') !!}

//define route name in route file then check with getName() method in view
Route::get('/', ['as'=>'homepage', 'uses'=>'[email protected]']);

@if(request()->route()->getName() == 'homepage')
   // 
@else
  //
@endif

Troubleshoot

Fix 419 Error —
//add one of these 2 code lines in view file
<form action="" method="post">
@csrf
</form>

<form action="" method="post">
{{ csrf_field() }}
</form>
Disable Debugbar —
//Add this line to .env file
DEBUGBAR_ENABLED=false

//call Debugbar::disable() in ServiceProvider
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        \Debugbar::disable();
    }
}
Fix Error: Class 'App\Http\Controllers\config' not found —
//include this line to enable the usafe of Config facade:
use Config;
Check Laravel Version —
//use command
php artisan --version

//view Application.php
class Application extends Container implements ApplicationContract, HttpKernelInterface
{
    /**
     * The Laravel framework version.
     *
     * @var string
     */
    const VERSION = '5.8.38';
 ....
}
Secure the .env File —
//.htaccess
<FilesMatch "^\.env">
    Order allow,deny
    Deny from all
</FilesMatch>
Include PHP Library File To Autoload —
"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories",
            "app/Libraries"
        ]
    },

User and Permission

Query Users with Specific Roles —
$inspectors = User::role('inspector')->get();
$users = User::role(['roleA', 'Role B'])->get();


$inspector = User::permission('inspect equipment')->get();

Variable

Check If Variable Exists with Blade Directive —
@isset($phoneName)
    {{ $phoneName}}
@endisset

@if(empty($user))
    <p>Guest</p>
@else
    <p>Hello, {{ $user->name }}</p>
@endif

//Laravel 5.7+: print quantity if it exists, otherwise print 0.00
{{ $qty ?? '0.00' }}
{{ $qty or '0.00' }}

@if(isset($student))
    {{ $student->name }}
@endif

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close