'Shorten the Controller Logic Laravel
I'm trying using Laravel login authentication using different guards but I found that there is some repetition within the store method in the Login Controller (the only difference is the guard used, all other logic are the same). I just can't find a way to shorten them into some other logic such as method(function) which can be reusable. So if there is possible way, Please help me out.
public function store(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('instructor')->attempt(['email' => $request->username, 'password' => $request->password])) {
if (auth('instructor')->user()->status === Instructor::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('instructor')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route('instructor.dashboard'));
}
if (Auth::guard('student')->attempt(['email' => $request->username, 'password' => $request->password])) {
if (auth('student')->user()->status === Student::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('student')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route('student.dashboard'));
}
return back()->with('error', 'Credentials provided do not match any record.');
}
Solution 1:[1]
This is probably not the best way to go about this, I'm sure there is a better solution, and @Aqib Javaed's seems to be it, but here's one way to shorten the code a bit that I could manage. It's not perfect but does the job done.
public function store(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('instructor')->attempt(['email' => $request->username, 'password' => $request->password])) {
$userType = 'instructor';
} elseif (Auth::guard('student')->attempt(['email' => $request->username, 'password' => $request->password])) {
$userType = 'student';
} else {
return back()->with('error', 'Credentials provided do not match any record.');
}
$modelName = ucwords($userType); //turn the user type to its corresponding model name
if (auth('$userType')->user()->status === $modelName::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('$userType')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route("$userType.dashboard"));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gowl |
