0
votes

So if a user wants to edit their own ticket they can do it from a form. But if they change the ID in the form, they can also edit another user's ticket. How do I prevent this?

public function edit(Ticket $ticket)
{
    $user = request()->user()->ticket()->get();

    if ($ticket === $user){
        return view('users.tickets.edit',['ticket' => $ticket,]);
    }
    else{
        abort(403);
    }
}

It automatically pick abort 403

This is the user Model

public function ticket(){
    return $this->belongsToMany(Ticket::class, 'ticket_user');
}

This is the ticket model

public function users() {
    return $this->belongsToMany(User::class, 'ticket_user');
}
2
Please explain a little more... The ticket belongs to multiple users and you want to check if the user (that belongs to the users associated with the ticket) can edit the ticket?jon
Yes correct but if the user does not belong to the ticket he can not enter that page.B.Simsek

2 Answers

1
votes

The logic itself could look like this:

$ticket->users->contains($request->user())

In your controller it could look like this:

use Illuminate\Http\Request;

public function edit(Request $request, Ticket $ticket)
{
    if (! $ticket->users->contains($request->user())) {
        return abort(403);
    }
  
    return view('users.tickets.edit', [
        'ticket' => $ticket
    ]);
}

Docs for Collection::contains.

I suggest looking into how you could exclude your authorisation logic into gates and policies.

0
votes

The right implementation for me looks like this.

The models:

*User
 id
 ...

*Ticket
 id
 ...

 UserTicket
 *id
 *ticket_id
 *user_id
 

When you create a ticket you have to create a new UserTicket for any user is able to edit the ticket.

Then you check if there is a record in UserTicket that has the user_id.

For example:

The Ticket model

public function users()
{
    return $this->hasManyThrough(UserTicket::class, User::class);
}

And the edit controller

public function edit(Ticket $ticket)
{
    $currentUser = request()->user();
    $ticketUsers = $ticket->users;

    // loop each ticketUser and check their id == $currentUser->id

}