Simplify Your Laravel Codebase: Best Practices for Readable and Concise Syntax

Eshan Dilmina
1 min readApr 9, 2024

--

Laravel offers various techniques to streamline your code, enhancing readability and maintainability. Below are examples of common syntax and their shorter, more readable counterparts:

Session Handling:

  • Session::get('cart') => session('cart')
  • $request->session()->get('cart') => session('cart')
  • Session::put('cart', $data) => session(['cart' => $data])

Request Input:

  • $request->input('name'), Request::get('name') => $request->name, request('name')
  • $request->has('value') ? $request->value : 'default'; => $request->get('value', 'default')

Redirects:

  • return Redirect::back() => return back()

Null Check:

  • is_null($object->relation) ? null : $object->relation->id => optional($object->relation)->id (PHP 8: $object->relation?->id)

View Data Passing:

  • return view('index')->with('title', $title)->with('client', $client) => return view('index', compact('title', 'client'))

Date Handling:

  • Carbon::now(), Carbon::today() => now(), today()

Service Container:

  • App::make('Class') => app('Class')

Query Builder:

  • ->where('column', '=', 1) => ->where('column', 1)
  • ->orderBy('created_at', 'desc') => ->latest()
  • ->orderBy('age', 'desc') => ->latest('age')
  • ->orderBy('created_at', 'asc') => ->oldest()
  • ->select('id', 'name')->get() => ->get(['id', 'name'])
  • ->first()->name => ->value('name')

By adopting these practices, you can simplify your Laravel codebase, making it more concise and easier to maintain without sacrificing functionality.

--

--

No responses yet