Search code examples
phplaravellaravel-routing

Get delete id in controller to delete mysql record


I have this in AuthController:

public function DelFunc() {

    if(Auth::check() === true) {
        $deleted = DB::delete('delete from funcionarios where id = ?',[$id]);
    }
    return redirect()->route('admin.login');
}

But I get this error: Undefined variable: id

I have this button in my view:

<a href="../admin/delFunc?id={{$empresa->id}}">
    <button class="btn btn-primary">Delete</button>
</a>

I know my question is simple, but, how can I get the id value on AuthController to delete this record?

I also have this route:

Route::get('/admin/delFunc', [App\Http\Controllers\AuthController::class, 'delFunc'])->name('delFunc');

Solution

  • A bunch of red flags here:

    • Why is this going into a controller called AuthController when it is working with a Funcionario object?
    • Why direct database queries instead of using Eloquent models?
    • You should not be deleting items by GET method, this is very dangerous.
    • Authentication is to be done by middleware, not by checking within every controller method.
    • And last, your method should also have a more conventional name like destroy.

    Route parameters are defined in the route definition with braces like "/admin/delete/{func}" and then bound to objects in the controller method definition.

    So, putting all that together, what it should look like is:

    <?php
    
    use App\Http\Controllers\FuncionarioController;
    use Illuminate\Support\Facades\Route;
    
    Route::middleware("auth")->group(function ($router) {
        $router->delete('/funcionario/{func}', [FuncionarioController::class, 'destroy'])
            ->name('funcionario.destroy');
    });
    

    And then in your controller:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Models\Funcionario;
    
    class FuncionarioController extends Controller {
    
        public function destroy(Funcionario $func)
        {
            $func->delete();
            return redirect()
                ->route('admin.login')
                ->with('success', __('Funcionario deleted'));
        }
    }
    

    And your view would look like this, assuming your value is passed in the $id variable:

    <form method="post" action="{{ route("funcionario.destroy", $id) }}">
        @method('DELETE')
        @csrf
        <button type="submit">{{ __("Delete") }}</button>
    </form>