Federico Ballarino
Federico Ballarino

Reputation: 11

Laravel 5.6 Delete by ID passed as function parameter

I am currently having an issue following a tutorial, when I call a controller method to delete a record by passing an $id via URI and trying to execute:

public function delete($id)
{
    //dd($id);
    $sql = 'DELETE * FROM albums WHERE id=:id';
    DB::delete($sql, ['id' => $id]);
    return redirect()->back();
}

I get this error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM albums WHERE id=?' at line 1 (SQL: DELETE * FROM albums WHERE id=:id)

The URI passed is /album/2/delete where 2 is the id I parse.

Upvotes: 1

Views: 107

Answers (3)

Ahmed Numaan
Ahmed Numaan

Reputation: 1062

Here is completed code:

public function delete($id)
{
    //dd($id);
    $sql = 'DELETE FROM albums WHERE id=:id';
    DB::delete($sql, ['id' => $id]);
    return redirect()->back();
}

Upvotes: 0

Geomi George
Geomi George

Reputation: 51

Remove * from query.Also in laravel use this code to delete.

DB::table('albums')
->where(['id' => $id])
->delete();

Don't write direct queries while you are using a framework

Upvotes: 0

Blue
Blue

Reputation: 22911

There is no need to include * in your DELETE query as you can't delete a column. It's already assuming you're deleting the entire row:

DELETE FROM albums WHERE id=:id

See the DELETE syntax in the MySQL documentation here.

Upvotes: 3

Related Questions