Question: Laravel pluck and findOrFail not returning correct row


Laravel pluck and findOrFail not returning correct row

Answers 1
Added at 2017-01-02 19:01

I am using the Gate facade to check whether a user can delete a row, or not.

 Gate::define('delete-cons', function ($user, $cons) {
        $c_id = Cons::findOrFail($cons)->pluck('c_id');
        return $user->c->id == $c_id;

If I output $cons, it returns 4.

4   2   1   Mr  Joe Bloggs  male    1234567 0   1_1474822931.png    2017-01-02 17:33:49 2017-01-02 17:33:49 NULL

The first column above is the primary key, so as we can see, it should return this row.

However, upon outputting $c_id after the query, it shows:

#items: array:4 [▼
    0 => 1
    1 => 1
    2 => 1
    3 => 2

I would've expected it to return the last result of 2, but it returns all 4 rows within the table!

Even if I manually type the ID of the row to get:

$c_id = Cons::findOrFail(4)->pluck('c_id');

It still returns all rows.

I'm aware I can use

$c_id = Cons::where('id', $cons)->pluck('c_id');

Which works correctly, but I'm following the Laravel Gate example, where FindOrFail throws an exception.

Many thanks.

nr: #1 dodano: 2017-01-02 19:01

You shouldn't use pluck() after findOrFail(), because it will just run query to get c_id from all rows. Do something like this instead:

$c_id = Cons::findOrFail($cons)->c_id;

If for some reason you want to use pluck(), do this:

$c_id = Cons::where('column', $cons)->pluck('c_id');
Source Show
◀ Wstecz