2.5 Delete User (ok)
Last updated
Last updated
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use DB;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Arr;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$roles = Role::pluck('name', 'id')->all();
return view('users.create')->with(compact('roles'));
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$inputs = $request->all();
$inputs['password'] = bcrypt($inputs['password']);
$user = User::create($inputs);
$roles = $inputs['roles'];
$user->assignRole($roles);
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
$user = User::find($id);
return view('users.show')->with(compact('user'));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
$user = User::find($id);
$roles = Role::pluck('name', 'name')->all();
$userRole = $user->roles->pluck('name', 'name')->all();
return view('users.edit', compact('user', 'roles', 'userRole'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if (!empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = Arr::except($input, array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id', $id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('user.index');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
User::find($id)->delete();
return redirect()->route('user.index')->with('success', 'User deleted successfully');
}
}