0% found this document useful (0 votes)
9 views4 pages

Formation Laravel - Expert

Uploaded by

Sarah Boudjelaba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

Formation Laravel - Expert

Uploaded by

Sarah Boudjelaba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Gates AND Policies

1. Define a Gate in the AuthServiceProvider:

use Illuminate\Support\Facades\Gate;

public function boot()

$this->registerPolicies();

Gate::define('edit-post', function ($user, $post) {

// Check if the user can edit the given post

return $user->id === $post->user_id;

});

2. Using Gates in Controllers or Blade Views:

public function edit(Post $post)


{
// Authorize the user using the 'edit-post' gate
if (Gate::allows('edit-post', $post)) {
// User is authorized, proceed with editing
return view('posts.edit', compact('post'));
} else {
// User is not authorized, show an error or redirect
abort(403, 'Unauthorized action.');
}
}

In blade :
@can('edit-post', $post)

<a href="{{ route('posts.edit', $post) }}">Edit Post</a>

@endcan

3. Using Gates in Policies:

You can also use gates in policies. Create a policy using

php artisan make:policy PostPolicy --model=post

In the AuthServiceProvider

use App\Models\Post;
use App\Policies\PostPolicy;

protected $policies = [
Post::class => PostPolicy::class,
];

In post controller

$this->authorize('view', $post);

In postPolicy

public function view(User $user, post $post)


{
return false;
}
APÏ

In your routes/api.php file:

Route::get('/status', function (Request $request) {

return response()->json(['status' => 'ok', 'message' => 'Operation


successful']);
})->name('status');

php artisan make:controller Api/V1/PostController -r

2. URL:

Localhost/api/V1/status
Add new column in Database :

php artisan make:migration add_column_to_users_table --table=users

In the migration

public function up()


{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->nullable()->after('password')
->unique()
->default(null);

});
}

You might also like