// Login method public function login(Request $request){ $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)){ return redirect()->intended('/dashboard'); } return redirect('/login')->with('error', 'Invalid login credentials.'); } // Logout method public function logout(){ Auth::logout(); return redirect('/login'); }
// Validate and create new user public function register(Request $request){ $data = $request->validate([ 'name' => 'required|string', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|min:8|confirmed', ]); $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); Auth::login($user); return redirect('/dashboard'); }
// Update user profile details public function update(Request $request){ $data = $request->validate([ 'name' => 'required|string', 'email' => 'required|email|unique:users,email,' . auth()->user()->id, 'password' => 'nullable|string|min:8|confirmed', ]); $user = auth()->user(); $user->update([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); return back()->with('success', 'Profile updated successfully.'); }
// Assign role to user $user = User::findOrFail($userId); $user->assignRole('writer'); // Check if user has a specific role $user->hasRole('admin'); // Check if user has any of the given roles $user->hasAnyRole(['admin', 'writer']); // Get all users with a specific role $users = User::role('writer')->get(); // Revoke role from user $user->removeRole('writer');