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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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.

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.

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.

Why is Laravel so popular? Why is Laravel so popular? Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Laravel's Primary Function: Backend Development Laravel's Primary Function: Backend Development Apr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel (PHP) vs. Python: Development Environments and Ecosystems Laravel (PHP) vs. Python: Development Environments and Ecosystems Apr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

See all articles