I have an assignments table (columns assignment_id, staff_name, asset_id, department, date, status) Currently my assignments table contains details of assets assigned to staff members and their departments.
In code I want to check if the asset_id already exists with it's status = 'Active' then insertion should throws an error but if the asset_id already exists with it's status = 'Disable' the insertion should proceed even if it's the asset_id exists.
The status columns with value as 'Disable' means the asset is not currently assigned to someone on the other hand, status = 'Active' means the asset is currently assigned to someone since it's assigned to someone you cannot assigned to someone else as 'Active' again but can assign as 'Disable'
For Instance
Assignment_id Staff Asset_id Department Status Date
1 Reynold AIO002 Logistics Disable 12.03.2014
2 Kyle AIO002 Business Dev Disable 12.04.2014
3 Trisha AIO002 Revenue Active 25.06.2015
4 Mary AIO002 Waybill Active 21.09.2015
Assuming assignment_id '4' is the last insertion, it should throw an error and not insert because you can't have one asset currently assigned to different people but if it were to be 'Disable' then insert.
Here is Controller as well:
AssignmentsController
class AssignmentController extends Controller
{
public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignments = new Assignment;
$assignments ->assignment_id = $request->input('assignment_id');
$assignments ->staff_id = $request->input('staff_name');
$assignments ->asset_id = $request->input('asset_id');
$assignments ->department_id = $request->input('department');
$assignments ->date = $request->input('date');
$assignments ->status = $request->input('status');
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
$assignments ->save();
return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}
The below variable and if statement in the AssignmentsController always throws the error in the if statement when the asset_id already exist instead of checking it's status also and the insertion doesn't happen.
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
Please help if you understand it. Thanks in advance.