Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LaraBABA's avatar

Laravel constructor - How to use it correctly?

Hello,

I would like to know what is the best use of a constructor in Laravel please.

Let's say I have a controller for CRUD, would it make sense to have in my constructor:

$id = $request->id;

So each time I can then use this id in my update and delete functions.

The question is, what would happen if there isn't a request(ie: create function). Would I still be obliged to add: if($request){ $id = $request->id; }

Or would I be able to just leave it as: $id = $request->id;

I am just trying to understand the best use of a constructor.

Thank you.

0 likes
6 replies
salmon's avatar

You will define specific declarations i.e.$id = $request->id; in your methods rather than in your constructor.

i.e.

index(Request request) {
     $id = $request->id;
}

But you can use a constructors for things that applies to all methods - that you want to re-use during the session.

i.e.

   public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
rawilk's avatar

I agree with @salmon. Typically you pass variables to your controller methods either through the Request object, route parameters, or route model binding (which is still route parameters). Typically, at least for me, you use the constructor in a controller for dependency injection.

1 like
jlrdw's avatar

I am just trying to understand the best use of a constructor.

Use for things that apply every time the class is called:

As example from docs:

public function __construct()
{
    $this->middleware('auth');
}

Would apply to all methods:

LaraBABA's avatar

Thank you all for the replies.

So let's say I have 5 classes and 4 of them need the logic passing in the constructor, will it be ok to still run this constructor on the class that does not require it? Would this not be a waste of overheads? If yes how would you deal with the 5th class that does not require this logic in the constructor to run, can we stop the constructor to run on specific classes?

Snapey's avatar

Why add a line $this->id = $request->id

Why not just use $request->id wherever you need it?

It really disappoints me when I see stuff like

public function store(Request $request)
{
    $id = $request->id;

    $model = Model::find($id);

What was the point of creating a variable, just to use it once?

jlrdw's avatar

Have you viewed any of the basic beginning videos.

Jeffrey's basics series would probably clear up some of this.

Please or to participate in this conversation.