Make car rental admin using laravel 9 part 4: Management user

php artisan make:controller UserController --resource
Route::middleware(['auth'])->resource('/user', UserController::class);
<a class="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#collapsePages" aria-expanded="false" aria-controls="collapsePages">
<div class="sb-nav-link-icon"><i class="fas fa-users"></i></div>
Pelanggan
<div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
</a>
<div class="collapse" id="collapsePages" aria-labelledby="headingTwo" data-bs-parent="#sidenavAccordion">
<nav class="sb-sidenav-menu-nested nav accordion" id="sidenavAccordionPages">
<a class="nav-link collapsed" href="{{ route('user.index') }}">
Pelanggan
</a>
</nav>
</div>

Index

public function index(Request $request){
$search = $request->search;
$users = User::where('name', 'like', '%' . $search .'%')
->orWhere('email', 'like', '%' . $search .'%')
->latest()
->paginate(10);
return view('users.index', compact('users'));
}
public function gravatar(): Attribute{
$hash = md5(strtolower(trim($this->attributes['email'])));
return new Attribute(
get: fn () => "http://www.gravatar.com/avatar/$hash",
);
}

Create

public function create(){
return view('users.create');
}public function store(Request $request){
$data = $request->validate([
'name' => 'required',
'email' => 'required|email:rfc,dns|unique:App\Models\User,email',
]);
$data['password'] = Crypt::encrypt(Str::random(8));
if($request->file('image')){
$data['image'] = $request->file('image')->store('cars');
}
User::create($data);
return redirect()->route('user.index')->with('success', 'Data pelanggan berhasil ditambahkan');
}

Update

public function edit(User $user){
return view('users.edit', compact('user'));
}public function update(Request $request, User $user){
$data = $request->validate([
'name' => 'required',
'email' => 'required|email:rfc,dns',
]);
if($request->file('image')){
if($request->oldImage){
Storage::delete($request->oldImage);
}
$data['image'] = $request->file('image')->store('users');
}
$user->update($data);
return redirect()->route('user.index')->with('success', 'Data pelanggan berhasil diupdate');
}

Delete

if($user->image){
Storage::delete($user->image);
}
User::destroy($user->id);
return redirect()->route('user.index')->with('success', 'Data pelanggan berhasil dihapus');
@if($user->is_admin == 0)
<form class="d-inline" action="{{ route('user.destroy', $user->id) }}" method="POST">
@csrf
@method('delete')
<button class="btn btn-danger" onclick="return confirm('Hapus data mobil ini?')">Hapus</button>
</form>
@endif

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
M Alfa Riza

M Alfa Riza

FullStack Developer | Vue js | React js | Laravel