Search code examples
phplaravellaravel-5eloquent

Laravel Eloquent delete() not working


Documentation says:

$user = User::find($user_id);

$user->delete();

This doesnt work, however ProductColor::find($color_id) working. $color->delete() Doest return anything, DELETE FROM query doesn't even execute (as seen in debug bar).

But I can delete record with:

ProductColor::destroy($color_id);

Must be something I overlooked earlier, I'm new to Laravel.

I'm using store also, and it working as expected

public function store(Request $request)
    {
        $color = new ProductColor();
        $color->name = $request->color_name;
        $color->order = $request->color_order;
        $saved = $color->save();

        if ($saved) {
            return back()->with('message:success', 'Ok');
        } else {
            return back()->with('message:error', 'Error');
        }

    }

To sum up

This WORKS

public function destroy($color_id)
    {
        $deleted = ProductColor::destroy($color_id);

        if ($deleted) {
            return back()->with('message:success', 'Deleted');
        } else {
            return back()->with('message:error', 'Error');
        }
    }

This NOT

public function destroy($color_id)
{
  $color = ProductColor::find($color_id);

  $color->delete();
}

My Model

<?php

namespace Modules\Shop\Entities;

use Illuminate\Database\Eloquent\Model;
use Modules\Languages\Entities\Language;

class ProductColor extends Model
{
    protected $fillable = [];
    protected $table = 'product_colors';
}

Solution

  • Sorry, I've figured out the problem. My mistake to post this question.

    What I tried to do:

    $color = new ProductColor();
    $color->find($color_id);
    $color->delete();
    

    Should be:

    $color = ProductColor::find( $color_id );
    $color->delete();
    

    My problem was that I was scared about the IDE complaining about using non-static method 'find'