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!
Table of Contents
Laravel Code Snippets
Cache
Database
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;
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"
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
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
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
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
User and Permission
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