Home > Mobile >  Laravel can't Delete data, it can enter on destroy() function but it parameter return null
Laravel can't Delete data, it can enter on destroy() function but it parameter return null

Time:01-10

So i'm try to delete data on laravel using resource route. but the data remain and still return the function. Im also try to delete the Greens from destroy() parameter, it make $greens containing 'id'. but still, i want to keep destroy() parameter to be (Greens $greens), not just ($greens)

Controller :

    public function destroy(Greens $greens)
    {
        //dd($greens->id);
        Greens::destroy($greens->id);
        return redirect('/greens');
    }

Form :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>


    <table>
        @foreach ($data as $d)
        <tr>
            <td>
                {{$d['brand']}}
            </td>
            <td>
                <form action="/greens/{{$d['id']}}" method="POST">
                    @method('DELETE')
                    @csrf
                    <button>Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>


</body>

</html>

Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Greens extends Model
{
    use HasFactory;
    protected $primaryKey = 'id';
}

Route:

<?php

use App\Http\Controllers\GreensController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
Route::resource('/greens', GreensController::class);

i try to var_dump $greens->id but the result is null

CodePudding user response:

When you use Laravel Route Resource, there's a format you should follow, refer to this link: https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller

I can see here in your destroy function $greens is in plural, you should use the singlular form $green:

public function destroy(Greens $green)
{
    Greens::destroy($green->id);
    return redirect('/greens');
}

CodePudding user response:

You can simple do the following:

  1. Your model name needs to be singular so Green
  2. For the resource it should be Route::resource('greens', GreensController::class);

public function destroy($id)
{
   Green::find($id)->delete();
   return redirect('/greens');
}

In the form:

<form action="/greens/{{ $d->id }}" method="POST">
   @method('DELETE')
   @csrf
   <input type="submit" value="Delete" />
</form>
  • Related