1

I got an error when i want to use Policies to limit users access, when user access the system as guest, the system won't show edit button vice versa if user as admin the system will show the edit button. But i got an error when user are logged in as Admin and no error when user are not logged in. This are my error messages

oo few arguments to function App\Policies\InverterPolicy::update(), 1 passed in /Applications/XAMPP/xamppfiles/htdocs/PROJECT/ta/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 691 and exactly 2 expected

This are my blade

@can('update',App\Inverter::class)
    <a href="{{ route('inverters.edit',[$data->id]) }}"><button type="button" class="btn btn-warning" name="button">Edit</button></a>
@endcan

This are my Controllers

public function update(Request $request, Inverter $inverter)
{
  $this->authorize('update',$inverter);
  $data = $request->validate([
    'name'=>'bail|required|max:191',
    'warehouse_id'=>'bail|required|numeric',
    'company_id'=>'bail|required|numeric',
    'length'=>'numeric',
    'width'=>'numeric',
    'height'=>'numeric',
    'maxInputPower'=>'numeric',
    'maxInputVoltage'=>'numeric',
    'maxInputCurrent'=>'numeric',
    'MPPTOperatingRange'=>'numeric',
    'parallelInput'=>'numeric',
    'MPPTTrackers'=>'numeric',
    'nominalOutputPower'=>'numeric',
    'maxOutputPower'=>'numeric',
    'nominalOutputCurrent'=>'numeric',
    'maxOutputCurrent'=>'numeric',
    'ACFrequencyRange'=>'numeric',
    'THDI'=>'numeric',
    'efficiency'=>'numeric',
    'MPPTEfficiency'=>'numeric',
    'euroEfficiency'=>'numeric',
  ]);
  Inverter::find($inverter->id)->update($data);
  return redirect(action('InverterController@index'));
}

this are my policies

public function update(User $user, Inverter $inverter)
{
  return in_array($user->role,[
    'Admin',
  ]);
}
Martin Christopher
  • 389
  • 1
  • 7
  • 21

1 Answers1

2

When you call the can() method on a User using, as the second parameter, the class name instead of an instance, you're actually calling the method without the second parameter at all. Just make the $inverter nullable in your policy and it should be fixed:

public function update(User $user, Inverter $inverter = null)
{
  return in_array($user->role,[
    'Admin',
  ]);
}
Alessandro Benoit
  • 903
  • 10
  • 19
  • It worked, but i still don't understand what happened, but thanks a lot – Martin Christopher Nov 27 '19 at 08:00
  • 1
    By default generated Laravel policies assumes that you'll pass an instance of the object, not its name. So the can method would expected for a given Inverter instance `$inverter = Inverter::find(1)` to be passed to it as following: `@can('update', $inverter)`. In your specific case you're calling the policy using the class name (a string) instead: `@can('update', 'App\Inverter')`. Hope that this clarifies it. – Alessandro Benoit Nov 27 '19 at 08:06