skip to Main Content

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 AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

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

Route:

<?php

use AppHttpControllersGreensController;
use IlluminateSupportFacadesRoute;

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

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

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search