Home PHP Framework Laravel How to delete user in Laravel

How to delete user in Laravel

Apr 21, 2023 am 10:09 AM

The Laravel framework provides powerful functions to operate databases. One of the common functions is to delete records in the database. In many applications, we need to delete users. This article will explain how to delete a user in Laravel.

First, we need a user model. If you already have one, then skip this step. The following is a simple user model:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $guarded = [];
}
Copy after login

In this model, we use Laravel’s built-in Authenticatable class. A $guarded attribute is also defined, which tells Laravel which properties cannot be batch assigned. In this case, we are not restricting any properties.

Next, we need a controller to handle the operation of deleting the user. Suppose we already have a UserController controller and define a destroy method. This method will pass a user ID in the request and delete the corresponding user. Here is a basic UserController controller:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function destroy(Request $request)
    {
        $user = User::find($request->id);
 
        if ($user) {
            $user->delete();
            return redirect('/users')->with('success', 'User deleted successfully');
        }
 
        return redirect('/users')->with('error', 'User not found');
    }
}
Copy after login

In this controller we first get the user ID passed in the request and then look up the user via the User model Record. If the user is found, we call the delete method to delete the user record. If the user record does not exist, we will redirect to the user list page and display an error message.

Now, we need a route to handle delete user requests. The following is a routing definition:

Route::delete('/users/{id}', 'UserController@destroy')->name('users.delete');
Copy after login

In this routing, we use RESTful style routing. It maps the HTTP DELETE request to the destroy method of the UserController controller, and passes the parameter {id} in the request as a parameter to the method.

Next, we need a view to display the user list and perform deletion operations. Here is a simple user list view:

@extends('layouts.app')
 
@section('content')
    <div class="container">
        @if (session('success'))
            <div class="alert alert-success">
                {{ session('success') }}
            </div>
        @endif
 
        @if (session('error'))
            <div class="alert alert-danger">
                {{ session('error') }}
            </div>
        @endif
 
        <h3>Users</h3>
 
        <table class="table">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td>
                        <form action="{{ route(&#39;users.delete&#39;, $user->id) }}" method="POST">
                            @csrf
                            @method('DELETE')
 
                            <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    </div>
@endsection
Copy after login

In this view, we first check if there are any success or error messages. If there are, we display them. We then listed all users and placed a delete button at the end of each row. When the user clicks the delete button, we will submit a DELETE request in the form to the users.delete route, passing the user's ID as a parameter.

Now, we have completed the operation of deleting users in Laravel. When we click the delete button in the user list, we will execute the destroy method of the UserController controller, delete the corresponding user, and redirect the user to the user list page while displaying Success or error message.

Overall, deleting users in Laravel is very simple. We only need to build a controller, define the corresponding routes, build a view, and set up the relevant models. The Laravel framework provides many powerful tools to handle data operations, which allows us to quickly develop feature-rich applications.

The above is the detailed content of How to delete user in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which is better, Django or Laravel? Which is better, Django or Laravel? Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Which is better PHP or Laravel? Which is better PHP or Laravel? Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

Is Laravel a frontend or backend? Is Laravel a frontend or backend? Mar 27, 2025 pm 05:31 PM

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel's Versatility: From Simple Sites to Complex Systems Laravel's Versatility: From Simple Sites to Complex Systems Apr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

See all articles