I am working on a web application using Laravel-5.8. In the project, when I perform a store action or perform an update action, I have been able to set all other is_current to 0 apart from the newly created or updated one.
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
However, I have this observation, even when the checkbox (is_currrent) is not checked, my code still set all other is_current to 0. This should only happen when the checkbox is checked.
How do I achieve this?
Thank you.
Related
I want to get how many people or users viewed the notification,when the user click on notification it will open to profile page of user,so how do i get how many user viewed the notification i am kind lost touch with laravel,so help is appreciated
Table
public function notifcationCount(Request $request){
$input = $request->all();
$validator = Validator::make($input, [
'notifcationcount' => 'required'
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$notifcationCount=$request->notifcationcount;
$notification = NotificationCount::where('notification_view_count', $notifcationCount)->first();
$notification->notification_view_count = $notification->notification_view_count+1;
$notification->save();
if(!empty($notification)){
$success['status'] = 200;
return $this->sendResponse($success, 'notificationcount increased');
}
else
{
$success['status'] = 201;
return $this->sendResponse($success, 'notificationcount increase failed');
}
}
Take field in table notification_view_count when the user will click on notification then hit api to increment the notification_view_count by 1.
Replace NotificationModel with your notification model name,
Create function like this:
public function updateNotificationCount($notification_id)
{
$notification = NotificationModel::where('id', $id)->first();
$notification->notification_view_count = $notification->notification_view_count+1;
$notification->save()
}
Make new route for this action and hit that route from android app
Finally i have solved with increment,but thanks for the idea by #Ranjeet
public function notifcationCount(Request $request){
$input = $request->all();
$validator = Validator::make($input, [
'notifcationcount' => 'required'
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
$notifcationCount=$request->notifcationcount;
$notification = DB::table('notificationcount')->increment('notification_view_count',$notifcationCount);
$getCount = DB::table('notificationcount')->select('notification_view_count')->first();
if(!empty($getCount)){
$success['status'] = 200;
$success['Count'] = $getCount;
return $this->sendResponse($success, 'Notification Count increased');
}
else
{
$success['status'] = 201;
return $this->sendResponse($success, 'Notification Count increase failed');
}
}
after i added product data into database, this error page show me instead of routing to product page.
But, data is successful inserted.
ProductsController.php
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
// Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->addRows);
if ($val->fails()) {
return response()->json(['errors' => $val->messages()]);
}
if (!$request->ajax()) {
$requestNew = $request;
$requestNew['price'] = $request->price * 100;
$data = $this->insertUpdateData($requestNew, $slug, $dataType->addRows, new $dataType->model_name());
event(new BreadDataAdded($dataType, $data));
$this->updateProductCategories($request, $data->id);
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager.generic.successfully_added_new')." {$dataType->display_name_singular}",
'alert-type' => 'success',
]);
}
}
Plz help me
I am creating a web module, and want to get ID of table licensing level two parse into my create method. Hence each ID of level will have a task and the ID need to be stored within my licensing table as a foreign key which reflects ID in Level Two table. How could I solve this, anyone can give me a good suggestion or way on doing this
public function add_show($id)
{
$level = PreLicensingLevelTwo::where('id', $id)->first();
$level->prelicensingtask = PreLicensingTask::where('pre_licensing_level_two_id', $level->id)->with('staff', 'statusdesc', 'prelicensingtaskstaff')->get();
return view('staff.regulatory.statutory.approval.display',compact('level'));
}
public function create()
{
$staff = Staff::pluck('staff_name');
$status = PreLicensingStatus::pluck('status_description', 'id');
return view('staff.regulatory.statutory.approval.create', compact('staff','status'));
}
public function show($id)
{
$one = PreLicensingLevelOne::where('pre_licensing_main_id', $id)->get();
foreach ($one as $key => $license)
{
$license->two = PreLicensingLevelTwo::where('pre_licensing_level_one_id', $license->id)->get();
}
$rendered = view('staff.regulatory.statutory.approval.show')->with('one', $one)->render();
return response()->json(array('status' => 1, 'tableData' => $rendered));
}
With help from my working collegue this is how i able to solve the question i asked
public function store(Request $request)
{
$this->validate($request, [
'task_title' => 'required',
'task_description' => 'required',
'task_due_date' => 'required',
]);
$leveltwo = PreLicensingLevelTwo::find($request->input('pre_licensing_level_two_id'));
$prelicensingtask = new PreLicensingTask;
$prelicensingtask->task_title =$request->input('task_title');
$prelicensingtask->task_description =$request->input('task_description');
$prelicensingtask->task_due_date =$request->input('task_due_date');
$prelicensingtask->created_by_staff_id = Auth::user()->ref_user->staff_id;
$prelicensingtask->status = $request->input('status');
$prelicensingtask->pre_licensing_level_two_id = $leveltwo->id;
$prelicensingtask->pre_licensing_level_one_id = $leveltwo->pre_licensing_level_one_id;
$prelicensingtask->pre_licensing_main_id = $leveltwo->pre_licensing_main_id;
$prelicensingtask->centre_id = Auth::user()->ref_user->centre_id;
$prelicensingtask->save();
return redirect()->back();
}
enter code hereMy question about the combination filters in laravel by using eloquent.
I am trying to filter with a combination of the following:
username
Category
Sub_category
started_at
created_at
status
I use where conditions but it not working as required.
public function filter(Request $request, User $user)
{
$user = $user->newQuery();
// Search for a user based on their name.
if ($request->has('username')) {
$user->where('name', $request->input('username'));
}
// Search for a user based on their Category.
if ($request->has('Category')) {
$user->where('Category', $request->input('Category'));
}
// Search for a user based on their Sub_category.
if ($request->has('Sub_category')) {
$user->where('Sub_category', $request->input('Sub_category'));
}
// Search for a user based on their started_at.
if ($request->has('started_at')) {
$user->where('started_at', $request->input('started_at'));
}
// Search for a user based on their status.
if ($request->has('status')) {
$user->where('status', $request->input('status'));
}
// Continue for all of the filters.
// Get the results and return them.
return $user->get();
}
You should save your where conditions to the $user variable.
$user = $user->where($dbField, $request->input($requestParam));
For improved readability, I'd suggest using a loop with all of your filtering cases.
public function filter(Request $request)
{
$users = User::query();
$filters = [
'username' => 'name',
'Category' => 'Category',
'Sub_category' => 'Sub_category',
'started_at' => 'started_at',
'status' => 'status'
];
foreach ($filters as $requestParam => $dbField){
if ($request->has($requestParam)) {
$users = $users->where($dbField, $request->input($requestParam));
}
}
return $users->get();
}
Bear in mind $request->has does not check whether the parameter value is empty, use $request->filled if you wish so.
This is My examle refer this
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
$q->when($email,function ($query) use ($email){
$query->where('email',$email);
});
$q->when($username,function ($query) use ($username){
$query->where('username',$username);
});
$results = $q->get();
//code
}
Doing ->save() and ->update() only updates when changes made, I think, is this true?
Here's the relevant part of code in Illuminate\Database\Eloquent\Model#performUpdate:
protected function performUpdate(Builder $query, array $options = [])
{
$dirty = $this->getDirty();
if (count($dirty) > 0)
{
// runs update query
}
return true;
}
I typically update like this:
public function update(Requests\UpdatePetRequest $request, Pet $pet)
{
$pet->update($request->all());
return $pet;
}
I want to figure from ->save and from ->update if what field names were updated? Along with what was the old value and the new value.
I currently manually do this like this:
public function update(Requests\UpdatePetRequest $request, Pet $pet)
{
$changes = [];
if ($request->exists('name') && $request->name != $pet->name) {
$changes['name'] = array([
'old' => $pet->name,
'new' => $request->name
]);
}
if ($request->exists('avatar') && $request->avatar != $pet->avatar) {
$changes['avatar'] = array([
'old' => $pet->avatar,
'new' => $request->avatar
]);
}
if (!count($changes)) {
return response()->json(['error'=>'No properties changed'], 422);
}
$pet->update($request->all());
$body = json_encode($changes);
$message = new Message(['body' => $body, 'kind' => 'PET_UPDATE']);
}
Is there an automated way to do this?
You can't do that with update(), but you can use getDirty() before save():
$model = Model::find($id);
$model->fill($request->all());
$cahnges = $model->getDirty();
$model->save();
getDirty() will return you an array with changed columns only, for example:
['name' => 'New Name', 'address' => 'New Street, 12']