want to update array values in vuejs using laravel - laravel

i have an array values in update form. i need to update specific values when user change in textareas. it looks like this
In my vuejs data objects looks like this.
data() {
return {
jobs: [],
details: {
basic_id: this.$route.params.id,
work: this.jobs
}
};
},
and my update method i wrote like this.
updateDetails() {
this.loading = true;
this.updateWorkedPlaces(this.details)
.then(() => {
console.log("success");
this.loading = false;
})
.catch(() => {
this.loading = false;
});
}
i pass these values it my vuex action methods.
async updateWorkedPlaces({ commit }, payload) {
let job = await Api().put("works/" + payload.basic_id, payload.work);
commit("UPDATE_WORK", job);
},
i pass these values to my laravel backend update function. it looks like this.
public function update(Request $request, $id)
{
$work = $request->work;
$basic = $request->basic_id;
foreach ($request->work as $i => $id) {
$job = Job::findOrFail($basic);
$job->fill(['position' => $id['position'], 'address' => $id['address']])->save();
}
return response()->json(['message' => 'success']);
}
but when i pass these values to this function it shows me this error.
Invalid argument supplied for foreach()
how can i fix this error. anyone can help me?

i figure out my problem with this function
public function update(Request $request, $id)
{
$collection = $request->all();
for ($i = 0; $i < count($collection); $i++) {
Job::where('id', $collection[$i]['id'])
->update([
'position' => $collection[$i]['position'],
'address' => $collection[$i]['address']
]);
}
return response()->json(['collection' => $collection]);
}

Related

How do I update an existing entry in my database?

How can I update my database properly? I'd like to modify an entry for which I have the id for, but a 'net::ERR_EMPTY_RESPONSE' is returned. Below I have my Controller:
public function update(Request $request, $id)
{
$booking = Booking::query($id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
These are all defined in my home blade view:
const eventData = {
id: eventid,
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
How do I properly update start_date and end_date in my database?
Additionally, this is my Javascript used to fetch:
const eventid = arg.event.id;
const eventData = {
start: arg.event.start.toISOString(),
end: arg.event.end.toISOString(),
};
const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
console.log(csrfToken);
fetch(`/api/event/update/${eventid}`, {
method: 'PUT',
headers: {
"X-CSRF-Token": csrfToken
},
body: encodeFormData(eventData),
})
.then(response => console.log(response))
.catch(error => console.log(error));
console.log("Complete");
I'm not sure how you're passing the ID for the booking, but from what I can see on the above, the ID is being passed in the request. Try this:
public function update(Request $request)
{
$booking = Booking::findOrFail($request->id);
$booking->start_date = $request->start;
$booking->end_date = $request->end;
$booking->save();
return response()->json($booking);
}
Updating a record is straight forward all you've got to is
public function update(Request $request)
{
// find the record by it's ID and also update it on the fly if you don't need to process anything else
$updatedData = Booking::findOrFail($request->id)->update(['start_date' => $request->start, 'end_date' => $request->end]);
return response()->json($updatedData);
}

Display content for user and for admin

I would like that normal users don't see the pictures with a status of 0 (not visible) only the visible ones (status 1) but that admins can see everything.
Is this kind of solution viable or is there something cleaner to do?
The gates/policies are not adapted for that, I don't see any other solution to my knowledge, that's why I come to you
Thanks in advance
public function show($name)
{
if(Auth::user()->isAdmin()) {
$model = cache()->remember('model_show'.$name, Config::get('cache.ttl'), function() use ($name) {
return Model::where('name', $name)->with('pictures')->first();
});
$pictures = $model->pictures()->latest()->paginate(18);
} else {
$model = cache()->remember('model_show'.$name, Config::get('cache.ttl'), function() use ($name) {
return Model::where('name', $name)->with('visible_pictures')->first();
});
$pictures = $model->visible_pictures()->latest()->paginate(18);
}
return view('model.model')->with(['model' => $model, 'pictures' => $pictures]);
}
You can clean it up by using when function in the query itself.
public function show($name)
{
$model = cache()->remember('model_show'.$name, Config::get('cache.ttl'), function() use ($name) {
return Model::where('name', $name)->when( Auth::user()->isAdmin() , function ($q)
{
return $q->with('pictures');
}, function ($q)
{
return $q->with('visible_pictures');
})->first();
});
$pictures = $model->pictures()->latest()->paginate(18);
return view('model.model')->with(['model' => $model, 'pictures' => $pictures]);
}
or we could also use arrow functions
public function show($name)
{
$model = cache()->remember('model_show'.$name, Config::get('cache.ttl'), function() use ($name) {
return Model::where('name', $name)->when( Auth::user()->isAdmin() ,
fn($q) => $q->with('pictures') ,
fn($q) => $q->with('visible_pictures')
)->first();
});
$pictures = $model->pictures()->latest()->paginate(18);
return view('model.model')->with(['model' => $model, 'pictures' => $pictures]);
}

Call to a member function pro_events() on null

Hello I'm trying to fix this issue where the error
Call to a member function pro_events() on null
would not happen all the time. I'm not sure what's causing this.
Any idea how to prevent this error in case it would appear again? We just saw this error in the log but can't duplicate the issue. Thanks!
Organizer.php model
class Organiser extends MyBaseModel
{
protected $rules = [
'org_name' => ['required', 'unique:organisers,name'],
'email' => ['required', 'email', 'unique:organisers'],
'organiser_logo' => ['mimes:jpeg,jpg,png', 'max:10000'],
'terms_agreed' => ['required'],
'org_tags' => ['required'],
];
protected $messages = [
'org_name.required' => 'You must at least give a name for the event organiser.',
'org_name.unique' => 'Your desired organisation name is already taken.',
'organiser_logo.max' => 'Please upload an image smaller than 10Mb',
'organiser_logo.size' => 'Please upload an image smaller than 10Mb',
'organiser_logo.mimes' => 'Please select a valid image type (jpeg, jpg, png)',
];
public function pro_events() {
return $this->hasMany(\App\Models\ProEvent::class)->orderBy('event_date', 'asc');
}
SomeController.php
public function showPackageHome($organiser_id, $event_dummy = null, $event_id = null, $the_country = null, $package_type_id = null, $package_category_id = null)
{
date_default_timezone_set('Europe/London');
$now = Carbon::now();
$cacheKey = md5(vsprintf('%s.%s', [
$organiser_id,
'organiser_cache'
]));
$organiser = Cache::remember($cacheKey, 10, function() use ($organiser_id) {
return Organiser::find($organiser_id);
});
$cacheKey = md5(vsprintf('%s', [
'event_list_cache'
]));
$events = Cache::remember($cacheKey, 1, function() use ($organiser, $now) {
return $organiser->pro_events()
->where("event_status", "live")
->whereDate('event_date', '>=', $now->format("Y-m-d"))
->orderBy('event_date', 'asc')
->get();
});
ProEvent.php model
class ProEvent extends MyBaseModel
{
use SoftDeletes;
protected $table = 'pro_events';
You must go up in the call stack to find where the organizer_id comes from. A possible reason would be that the admin/loggedIn person may change the route manually and try to load an organizer that doesn't exist.
If you have a route like /organizer/{organizer_id}, then you must make sure that the provided ID actually exists in db. One way to do it would be to use findOrFail instead of find and to catch the thrown exception in case the organizer doesn't exist.
public function showPackageHome($organiser_id, $event_dummy = null, $event_id = null, $the_country = null, $package_type_id = null, $package_category_id = null)
{
date_default_timezone_set('Europe/London');
$now = Carbon::now();
$cacheKey = md5(vsprintf('%s.%s', [
$organiser_id,
'organiser_cache'
]));
$organiser = Cache::remember($cacheKey, 10, function() use ($organiser_id) {
return Organiser::findOrFail($organiser_id);
});
$cacheKey = md5(vsprintf('%s', [
'event_list_cache'
]));
$events = Cache::remember($cacheKey, 1, function() use ($organiser, $now) {
return $organiser->pro_events()
->where("event_status", "live")
->whereDate('event_date', '>=', $now->format("Y-m-d"))
->orderBy('event_date', 'asc')
->get();
});
}
In your controller method you can actually catch the exception and display something to the user:
public function yourControllerMethod(Illuminate\Http\Request $request)
{
// something more here
try {
$events = $this->showPackageHome($request->get('organizer_id'), /* the other parameters */);
return $this->view(..., ['events' => $events]);
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
// The organizer couldn't be found
return redirect()->back()->withErrors(['organizer-not-found' => 'The organizer could not be found'])
}
}
i think it's because the instance of Organizer where you called pro_events() function was null.

How To Create Conditional for Unique Validation (UPDATE/PATCH) on Form Request

I'm trying to get my controller cleaner by moving 'validation request' into a form request called 'BookRequest'.
The problem is on the update process, I try to create a condition to check, if it PATCH or POST with the following codes
MyRequest.php
public function rules()
{
// Check Create or Update
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
}
else
{
$a_rules = 'required|string|size:6|unique:books,column2';
$b_rules = 'sometimes|string|size:10|unique:books,column3';
}
return [
'column1' => 'required|string|max:100',
'column2' => $a_rules,
'column3' => $b_rules,
'column4' => 'required|date',
'column5' => 'required|in:foo,bar',
'column6' => 'required',
'column7' => 'required',
'column8' => 'required',
];
}
.$this->get('id') it failed, the form still treat the unique on the update.
Controller#update
public function update($id, BookRequest $request)
{
$book = Book::findOrFail($id);
$input = $request->all();
$book->update($request->all());
return view('dashboards.book');
}
Controller#edit
public function edit($id)
{
$book = Book::findOrFail($id);
return view('dashboards.edit', compact('book'));
}
Controller#create
public function create()
{
return view('dashboards.create');
}
Controller#store
public function store(BookRequest $request)
{
$input = $request->all();
$book = Book::create($input);
return redirect('dashboards/book/index');
}
I try the alternative .$book->id, and it throw me an ErrorException Undefined variable: book
Any suggestion? I'm using Laravel 5.2 by the way
You are using book as your route parameter but trying to get with id. try this-
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
}
Hope it helps :)

Figure what fields `save()` acted on if any (detecting changes)

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']

Resources