Dylano236
Dylano236

Reputation: 317

Calling custom class method with a parameter in laravel route

So I have this function that is going to be used 1 as an artisan command or 2 as a link a user can use.

Here's the function:

public function saveAll($whatLocation)
    {
      $userSaved = $this->saveUsersData();
      $componentSaved = $this->saveComponentsData();
      $issueSaved = $this->saveIssuesData();
      $timelogSaved = $this->saveTimelogsData();
      if($userSaved === 1 && $componentSaved === 1 && $timelogSaved === 1)
      {
        $this->allSaved = 1;
      }
      if($whatLocation != "artisanCommand")
      {
        return redirect()->back();
      }
      else
      {
        return $this->allSaved;
      }

    }

The idea is that if it's coming from an artisan console command I created I pass "artisanCommand" but if it's coming from a route it pulls my api data and re-directs to the previous page.

Here's the problem:

in the web routes file I now can't call a function that has a parmater?

Route::get('/pull-and-save-api-data', [App\Classes\SaveApiData::class, 'saveAll'])->name('pull-and-save-api-data');

This works if there's no paramater on the function, but will not work now that there's a parameter??

I've tried:

Route::get('/pull-and-save-api-data', [App\Classes\SaveApiData::class, 'saveAll("notcommand")'])->name('pull-and-save-api-data');

Route::get('/pull-and-save-api-data/{notcommand}', [App\Classes\SaveApiData::class, 'saveAll'])->name('pull-and-save-api-data');

neither work?

Upvotes: 2

Views: 3440

Answers (1)

lagbox
lagbox

Reputation: 50491

How about you just make a default argument for the function since you don't have a value to pass to it from the route?

public function saveAll($whatLocation = null)

I wouldn't be calling your method directly from a route like that; have the route go to a Controller and have that Controller interact with the class/lib you need.

If you really had to have a value passed into it from the route you can set a default value:

Route::get('/pull-and-save-api-data', [App\Classes\SaveApiData::class, 'saveAll'])
    ->name('pull-and-save-api-data')
    ->defaults('whatLocation', 'notArtisan');

Upvotes: 6

Related Questions