Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter already requested data

Tags:

php

laravel

There is a function which returns all tickets. I have two roles: 1-Moderator(can see all tickets), 2-Client(can see own tickets). So I request all tickets, then I check if user is client, then I need to filter out and show his own tickets. Ticket has user_id field. I think i can do with foreach or there is a better option?

$tickets = Ticket::all();
// check whether authenticated user is client
if (auth()->user()->role_id == 2) {

}

return new TicketsResourceCollection($tickets);
like image 205
Danabek Duisekov Avatar asked Feb 18 '26 07:02

Danabek Duisekov


2 Answers

You can directly filter out data using user_id:

if (auth()->user()->role_id == 1) {
    $tickets = Ticket::all();
} else {
    $tickets = Ticket::where('user_id', auth()->user()->id)->get();
}
like image 196
Amit Senjaliya Avatar answered Feb 19 '26 19:02

Amit Senjaliya


Yeah, you can use Laravel Scope for that, you can write code in your Ticket model like this :

public function scopeClient($query)
{
    return $query->where('user_id', auth()->user()->id);
}

Then you can call your ticket that already scoped like this :

Ticket::client();
like image 20
Adrian Edy Pratama Avatar answered Feb 19 '26 20:02

Adrian Edy Pratama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!