search
HomePHP FrameworkLaravelHow 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 = [];
}

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');
    }
}

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');

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>
        @if (session('success'))
            <div>
                {{ session('success') }}
            </div>
        @endif
 
        @if (session('error'))
            <div>
                {{ session('error') }}
            </div>
        @endif
 
        <h3 id="Users">Users</h3>
 
        <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>id) }}" method="POST">
                            @csrf
                            @method('DELETE')
 
                            <button>Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    </div>
@endsection

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
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
Alternatives to Laravel for Full-Stack Development: Comparing FrameworksAlternatives to Laravel for Full-Stack Development: Comparing FrameworksApr 30, 2025 am 12:26 AM

If you are looking for alternatives to Laravel, Node.jswithExpress.js, Django, RubyonRails and ASP.NETCore are optional options. 1.Node.jswithExpress.js is suitable for projects that require high performance and scalability. 2.Django is suitable for projects that require rapid development and full functionality. 3.RubyonRails is suitable for rapid prototyping and flexible development. 4. ASP.NETCore is suitable for high traffic and cross-platform development, but the learning curve is steep.

Project Management Powerhouses: Keeping Distributed Teams Organized and On TrackProject Management Powerhouses: Keeping Distributed Teams Organized and On TrackApr 30, 2025 am 12:20 AM

Thekeychallengesinmanagingdistributedteamsarecommunicationgaps,timezonedifferences,andtaskmanagement.Projectmanagementtoolshelpovercomethesechallengesby:1)enhancingcommunicationthroughplatformslikeSlackandMicrosoftTeams,2)managingtimezonedifferencesw

Management from a Distance: Leading and Empowering Distributed Teams EffectivelyManagement from a Distance: Leading and Empowering Distributed Teams EffectivelyApr 30, 2025 am 12:12 AM

The key to leading a remote team is to use technology, build trust and develop personalized strategies. 1) Use communication tools and task management systems to ensure clear task allocation and status updates. 2) Avoid burnout through asynchronous communication and enhance productivity. 3) Incentive team members through authorization and setting clear goals. 4) Pay attention to team satisfaction and collaboration, and conduct comprehensive inspections regularly.

Tech Troubles: Ensuring Equitable Access to Tools and Resources for Distributed Team MembersTech Troubles: Ensuring Equitable Access to Tools and Resources for Distributed Team MembersApr 29, 2025 am 12:40 AM

Methods to ensure that distributed team members have fair access to tools and resources include: 1) using low-bandwidth alternatives, such as asynchronous video or text updates, to solve connection problems; 2) setting up core overlapping working hours and providing flexible working hours to manage time zone differences; 3) adapt to different cultural needs through translation functions and cultural awareness training. These strategies help create an inclusive and efficient remote working environment.

Instant Messaging Must-Haves: Fostering Real-Time Communication in Remote SettingsInstant Messaging Must-Haves: Fostering Real-Time Communication in Remote SettingsApr 29, 2025 am 12:38 AM

Forenhancingremotecollaboration,aninstantmessagingtoolmusthave:1)reliabilityforconsistentmessagedelivery,2)anintuitiveuserinterfaceforeasynavigation,3)real-timenotificationstostayupdated,4)seamlessfilesharingforefficientdocumentexchange,5)integration

Have you ever faced any challenges while working in distributed teams?Have you ever faced any challenges while working in distributed teams?Apr 29, 2025 am 12:35 AM

Thebiggestchallengeofmanagingdistributedteamsiscommunication.Toaddressthis,usetoolslikeSlack,Zoom,andGitHub;setclearexpectations;fostertrustandautonomy;implementasynchronousworkpatterns;andintegratetaskmanagementwithcommunicationplatformsforefficient

What are the security improvements in the new Laravel version?What are the security improvements in the new Laravel version?Apr 29, 2025 am 12:17 AM

Laravel's latest version has significantly improved security, including: 1. Enhanced CSRF protection, through a more robust token verification mechanism; 2. Improved SQL injection protection, through an enhanced query construction method; 3. Better session encryption to ensure user data security; 4. Improved authentication system, supporting finer granular user authentication and multi-factor authentication (MFA).

Time Zone Tango: Navigating Scheduling Conflicts in a Global WorkforceTime Zone Tango: Navigating Scheduling Conflicts in a Global WorkforceApr 29, 2025 am 12:13 AM

Tonavigateschedulingconflictsinaglobalworkforce,usetechnology,empathy,andstrategicplanning:1)EmploytoolslikeWorldTimeBuddyorCalendlyforscheduling;2)Rotatemeetingtimestoensurefairness;3)Establishcorehoursforoverlap;4)Beculturallysensitiveandflexiblewi

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools