Tisuchi's Blog

A Laravel Artisan

Let's do Laravel code refactoring

Posted on 26 Nov 2018
Image

Sometimes, we have some code that we can do refactor more. In this post I will show you how to do refactor a traditional code and make it more optimized.

Let's imagine that, as an author, you have some events. Now you need to show your events like the following code-

namespace App\Http\Controllers;

use Auth;
use App\Event;
use Illuminate\Http\Request;

class MyEventsController extends Controller
{
    public function index()
    {
    	$events = Event::where('users_id', Auth::id())->latest()->paginate(100);

        return view('folder.my-events')
                ->with('events', $events);
    }
}

Sure enough, many of Laravel developer follow this types of code, including me. Nothing wrong with that, right?

Waitt... Yeah, it's true, nothing wrong, but still can optimize this code.

I end up with the following code-

public function index()
    {
    	$events  = Auth::user()->load('events');

        return view('folder.my-events')
                ->with('events', $events);
    }

I believe this is more optimized than the previous code. What do you think?

If you have any other way to optimized that, feel free to share.