0
votes

I am trying to make authorization for users to some contents restrictions in view file, as i know that the only Authorization between laravel supported auth (gate,middleware) that can be used in view file is (policy) auth. And policy auth is working by using laravel models, while my data sources is not model, i am just getting data from some webservices.

I created a new policy (isPlatinum)

    <?php

namespace App\Policies;

use App\User;
use App\WebUser;
use Illuminate\Auth\Access\HandlesAuthorization;

class isPlatinum
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    public function view(WebUser $user){
        return $user->user->subscription->type === 'platinum';
    }

}

Notice: the App\WebUser is not a model file , it's just a class that get user info from webservices.

In my blade view file

@cannot('view',$isPlatinum)
        This page is for Platinum Users
        @endcannot

giving error

Undefined variable: isPlatinum (View: 

I know that i supposed to use Laravel Policy Auth only for models, in my situation, what is the right laravel auth i should use and i can use is inside view file?

1

1 Answers

0
votes

You did not pass isPlatinum variable to view. You can share data with all views:

Create a Service Provider as follows:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // method to fetch the webUser?
        // $webUser = ;
        View::share('isPlatinum', $webUser->user->subscription->type === 'platinum');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}