1
votes

I want to give all users the option to 'detach' a row from the pivot table - alert_criteria, but only if they own the 'criteria', which is linked by 'criteria_id' in the pivot table.

Relationship

An Alert belongsToMany Criteria.

A Criteria belongsToMany Alerts.

A User belongsToMany Criteria.

They are currently viewing the data of the pivot table through:

$matches = Criteria::whereUserId( Auth::id() )
        ->has('alerts')
        ->get();

I want them to have the functionality to be able to delete any of their rows from the pivot table.

Within my view, I can access each pivot table row's ID and post to the controller through:

{{ Form::open(array('route' => array('archiveMatch', $alert->id), 'role'=>'form')) }}
    @foreach($matches as $match)
        @foreach($match->alerts as $alert) 
            {{$alert->id}}
        @endforeach
    @endforeach
{{ Form::close() }}

I initially thought of:

public function postArchiveMatch($id)
    {
        DB::delete('delete from alert_criteria where id = ?' , array($id));
    }

But, I want to check if the user actually own's this pivot table row. As far as I am aware, anyone who knows this URL can delete pivot table rows even if they don't own the 'criteria':

  Route::post('users/match/destroy/{id}', 
    array('as' => 'archiveMatch', 'uses' => 'UsersController@postArchiveMatch'));

The only long winded way I can think of is:

Get criteria_id relating to alert_criteria.id. (from the form post).

Get all criteria where user_id = auth::id

Check to see if the 'criteria_id' is in the list. If not, that means the user doesn't own it.

I'm pretty sure I'm over complicating things but any help would be hugely appreciated.

1
You already know which criteria that the user owns. They are in $matches.Ben Harold
But when the user is wanting to delete a row, they're posting the ID from the pivot table, not the criteria_id associated with it.user860511

1 Answers

1
votes

You could specify a range of criteria_id in your delete query to limit the scope of the query. I'm thinking something along the lines of:

public function postArchiveMatch($id)
{
    $myCriteriaIds = Db::table('criteria')->select('id')
                                          ->where('user_id', '=', Auth::id())
                                          ->get()
                                          ->toArray();

    $myCriteriaIds = explode(',', $myCriteriaIds);

    DB::table->('alert_criteria')
             ->where('id', $id)
             ->where('criteria_id', 'IN', $myCriteriaIds)
             ->delete();
}