Search code examples
laravelauthorizationlaravel-5.8policies

Laravel Policies Via blade template


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',
  ]);
}

Solution

  • 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',
      ]);
    }