ÔõÑùÔÚLaravelÖÐɾ³ýÓû§
laravel¿ò¼ÜÌṩÁËÇ¿Ê¢µÄ¹¦Ð§À´²Ù×÷Êý¾Ý¿â¡£ÆäÖÐÒ»¸ö³£¼ûµÄ¹¦Ð§ÊÇɾ³ýÊý¾Ý¿âÖеļͼ¡£ÔÚÐí¶àÓ¦ÓÃÖУ¬ÎÒÃÇÐèҪɾ³ýÓû§¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚlaravelÖÐɾ³ýÓû§¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÒ»¸öÓû§Ä£×Ó¡£ÈôÊÇÄãÒѾÓÐÁË£¬ÄÇô¾ÍÌø¹ýÕâÒ»²½¡£ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄÓû§Ä£×Ó£º
<?php namespace App; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { protected $guarded = []; }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÄ£×ÓÖУ¬ÎÒÃÇʹÓÃÁËLaravelÄÚÖõÄAuthenticatableÀà¡£»¹½ç˵ÁËÒ»¸ö$guardedÊôÐÔ£¬Ëü¸æËßLaravelÄÄЩÊôÐÔ²»¿É±»ÅúÁ¿¸³Öµ¡£ÔÚ±¾ÀýÖУ¬ÎÒÃÇûÓÐÏÞÖÆÈκÎÊôÐÔ¡£
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÒ»¸ö¿ØÖÆÆ÷À´´¦Àíɾ³ýÓû§µÄ²Ù×÷¡£¼ÙÉèÎÒÃÇÒѾÓÐÁËÒ»¸öUserController¿ØÖÆÆ÷£¬²¢ÇÒ½ç˵ÁËÒ»¸ödestroyÒªÁ죬Õâ¸öÒªÁ콫ÔÚÇëÇóÖÐת´ïÒ»¸öÓû§ID£¬²¢É¾³ýÏìÓ¦µÄÓû§¡£ÏÂÃæÊÇÒ»¸ö»ù±¾µÄUserController¿ØÖÆÆ÷£º
<?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'); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸ö¿ØÖÆÆ÷ÖУ¬ÎÒÃÇÊ×ÏÈ»ñÈ¡ÇëÇóÖÐת´ïµÄÓû§ID£¬È»ºóͨ¹ýUserÄ£×Ó²éÕÒÓû§¼Í¼¡£ÈôÊÇÕÒµ½ÁËÓû§£¬ÎÒÃÇŲÓÃdeleteÒªÁìÀ´É¾³ýÓû§¼Í¼¡£ÈôÊÇÓû§¼Í¼²»±£´æ£¬ÎÒÃǽ«Öض¨Ïòµ½Óû§ÁбíÒ³Ã棬²¢ÏÔʾһ¸ö¹ýʧÐÂÎÅ¡£
ÏÖÔÚ£¬ÎÒÃÇÐèÒªÒ»¸ö·ÓÉÀ´´¦Àíɾ³ýÓû§ÇëÇó¡£ÏÂÃæÊÇÒ»¸ö·Óɽç˵£º
Route::delete('/users/{id}', 'UserController@destroy')->name('users.delete');
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸ö·ÓÉÖУ¬ÎÒÃÇʹÓÃÁËRESTfulÆøÑæÆøÑæµÄ·ÓÉ¡£Ëü½«HTTP DELETEÇëÇóÓ³Éäµ½UserController¿ØÖÆÆ÷µÄdestroyÒªÁ죬²¢½«ÇëÇóÖеIJÎÊý{id}×÷ΪҪÁìµÄ²ÎÊýת´ï¡£
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÒ»¸öÊÓͼÀ´ÏÔʾÓû§ÁбíºÍÖ´ÐÐɾ³ý²Ù×÷¡£ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄÓû§ÁбíÊÓͼ£º
@extends('layouts.app') @section('content') <div> @if (session('success')) <div> {{ session('success') }} </div> @endif @if (session('error')) <div> {{ session('error') }} </div> @endif <h3>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
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÊÓͼÖУ¬ÎÒÃÇÊ×Ïȼì²éÊÇ·ñÓÐÈκÎÀֳɻò¹ýʧÐÂÎÅ¡£ÈôÊÇÓУ¬ÎÒÃǽ«ËüÃÇÏÔʾ³öÀ´¡£È»ºó£¬ÎÒÃÇÁгöËùÓÐÓû§£¬²¢ÔÚÿÐÐĩβ°²ÅÅÁËÒ»¸öɾ³ý°´Å¥¡£µ±Óû§µã»÷ɾ³ý°´Å¥Ê±£¬ÎÒÃǽ«ÔÚ±íµ¥ÖÐÌá½»Ò»¸öDELETEÇëÇóµ½users.delete·ÓÉ£¬²¢×ª´ïÓû§µÄID×÷Ϊ²ÎÊý¡£
ÏÖÔÚ£¬ÎÒÃÇÒѾÍê³ÉÁËLaravelÖÐɾ³ýÓû§µÄ²Ù×÷¡£µ±ÎÒÃÇÔÚÓû§ÁбíÖеã»÷ɾ³ý°´Å¥Ê±£¬ÎÒÃǽ«Ö´ÐÐUserController¿ØÖÆÆ÷µÄdestroyÒªÁ죬ɾ³ýÏìÓ¦µÄÓû§£¬²¢½«Óû§Öض¨Ïòµ½Óû§ÁбíÒ³Ã棬ͬʱÏÔʾÀֳɻò¹ýʧÐÂÎÅ¡£
×ܵÄÀ´Ëµ£¬ÔÚLaravelÖÐɾ³ýÓû§ºÜÊǼòÆÓ¡£ÎÒÃÇÖ»ÐèÒª¹¹½¨Ò»¸ö¿ØÖÆÆ÷£¬½ç˵ÏìÓ¦µÄ·ÓÉ£¬¹¹½¨Ò»¸öÊÓͼ£¬²¢ÉèÖúÃÏà¹ØµÄÄ£×Ó¼´¿É¡£Laravel¿ò¼ÜÌṩÁËÐí¶àÇ¿Ê¢µÄ¹¤¾ßÀ´´¦ÀíÊý¾Ý²Ù×÷£¬ÕâʹµÃÎÒÃÇ¿ÉÒÔ¿ìËٵؿª·¢¹¦Ð§¸»ºñµÄÓ¦ÓóÌÐò¡£
ÒÔÉϾÍÊÇÔõÑùÔÚLaravelÖÐɾ³ýÓû§µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡