Change function of Policies

0

I am trying to modify the Policies function that is currently this:

public function pass(User $user, Product $product)
{
   return $user->id == $product->user_id;
}

Let's see if I explain myself well .. I have some products that when trying to access them, check that the id of the user is the same as the user_id of the product who tries to access everything here perfect but what I also need is to create some products that are accessible to them by all users without restrictions that all users regardless of their id have access to them. for example I thought about using the user_id 1 in all products without restriction but do not consider how to make the function of free access to all products with user_id 1 any idea ??

    
asked by Lendy Rodriguez Silva 19.10.2018 в 11:55
source

1 answer

1

I understand that your use case is the following:

There are products that can be accessed by all users and another group of products that have restricted access based on user_id of the product.

Based on this I propose two ways.

Mode 1

You add a value in the product table that indicates if the product is restrictive for the indicated user.

1 - Create a migration and add is_restricted as Boolean (or modify the initial):

php artisan make:migration add_is_restricted_column_to_products_table --table=products

then in AddIsRestrictedColumnToProductsTable.php :

Schema::table('products', function (Blueprint $table) {
            $table->boolean('is_restricted')->default(true)->after('user_id');
        });

2 - Run your migration.

3 - Modify your policy:

public function pass(User $user, Product $product)
{
    if ($product->is_restricted)
    {
        return $user->id == $product->user_id;
    }
    return true;
}

Mode 2

That you set the value of user_id in the product table to null in case this product is accessed by all. So, you can compare in your policy:

public function pass(User $user, Product $product)
{
    if ( ! is_null($product->user_id))
    {
        return $user->id == $product->user_id;
    }
    return true;
}

You can include an attribute in your product table that determines whether that product is accessible by all or only by a certain group of users.

    
answered by 19.10.2018 / 15:51
source