To implement user permissions based on roles in Laravel, you can use policies or directly apply conditions in your query. Here's a simple approach using Eloquent to achieve the desired functionality:
-
Define User Roles: Ensure that your
userstable has a column to define roles, for example,role. You might have roles likesuper_adminanduser. -
Query Logic: When fetching sales invoices, check the user's role and adjust the query accordingly.
Here's a code example to demonstrate this:
// Assuming you have a User model and a SalesInvoice model
use App\Models\SalesInvoice;
use Illuminate\Support\Facades\Auth;
public function getSalesInvoices()
{
$user = Auth::user(); // Get the currently authenticated user
if ($user->role === 'super_admin') {
// If the user is a super admin, retrieve all sales invoices
$salesInvoices = SalesInvoice::all();
} else {
// If the user is not a super admin, retrieve only their sales invoices
$salesInvoices = SalesInvoice::where('user_id', $user->id)->get();
}
return $salesInvoices;
}
Explanation:
-
Role Check: The code checks the role of the authenticated user. If the user is a
super_admin, it retrieves all sales invoices. Otherwise, it filters the sales invoices to only those created by the user. -
Eloquent Relationships: Ensure that your
SalesInvoicemodel has a relationship defined to theUsermodel, like so:// In SalesInvoice model public function user() { return $this->belongsTo(User::class); } -
Authentication: This example uses Laravel's built-in authentication to get the current user with
Auth::user().
This approach is straightforward and leverages Laravel's Eloquent ORM to handle the database queries efficiently. If your application grows more complex, consider using Laravel's authorization features like Gates and Policies for more granular control.