Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel function with optional parameter

Tags:

php

laravel

In my web file, I have a route that accepts a $id as a value to be passed to a function within my PagesController. However, I want the function to still execute and show the intended form even when the $id is not passed to the function.

web.php file

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

PagesController.php file

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

makeRequest.blade.php

<input type="text" class="form-control" value="{{$target->inst_name}}" required disabled>  

I want the page to display details from the database with the $id when provided or have empty spaces when the $id isn't provided.

like image 399
Nana Qhuacy Avatar asked Dec 05 '22 10:12

Nana Qhuacy


1 Answers

As the Laravel Documentation states: Use Optional Parameters like this:

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

Controller

public function makeRequest($id = null)
    {
        if(!empty($id)){
            $target = User::find($id);
            return view('pages.makeRequest')->with('target', $target); 
        } else {
            return view('pageslist'); ///set default list..
        }        
    }
like image 98
Jignesh Joisar Avatar answered Dec 07 '22 23:12

Jignesh Joisar