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

NanaQhuacy's avatar

Laravel function with optional parameter

In my web file, I have a route


Route::get('/request/{id}', 'PagesController@makeRequest');


and in my PagesController, I have a function


public function makeRequest($id)
    {
        if(!empty($id)){
            $target = Partner::find($id);
        }
        return view('pages.makeRequest')->with('target', $target);
    }

what I want to achieve is to have the page fetch some details when provided the $id but remain blank if no $id is provided.

Any help will be greatly appreciated.

0 likes
7 replies
HUGE_DICK_10_INCHES's avatar

{id?} add question mark for optional

Or even like this:

Route::get('/request/{partner}', 'PagesController@makeRequest');
public function makeRequest(Partner $partner)
    {
        return view('pages.makeRequest', compact('partner'));
    }
NanaQhuacy's avatar

@SKYCODER - Thanks so much.

I tried a combination of both methods. Good news is, without the $id, page displays with an empty space where I wanted it. Bad news is it still remains empty when the $id is passed. I even tried

return compact('partner');

and it returned an empty array.

HUGE_DICK_10_INCHES's avatar

@NANAQHUACY - Which means there is no Partner with that id, id must exist in partner table. You can try dd($partner) instead of returning, to check is it null or not.

NanaQhuacy's avatar

@SKYCODER - There is a partner with that id alright. In the end, what I did was to create a different form that wasn't echoing the passed result. So in the false section, I called that form instead.

ialexreis's avatar

@nanaqhuacy You can try to set a default value to the parameter, for example

public function makeRequest($id=null)

or

public function makeRequest($id='')

Don't know if that works under your case but it worths a try

Snapey's avatar
Route::get('/request/{id?}', 'PagesController@makeRequest');

    public function makeRequest($id = null)
    {
    $target = null;

        if($id){
            $target = Partner::findOrFail($id);
        }

        return view('pages.makeRequest')->with('target', $target);
    }

1 like
TauheedHussain's avatar

public function makeRequest($id='') { $target = Partner::find($id); return view('pages.makeRequest')->with('target', $target); }

Please or to participate in this conversation.