Data that has been edited is not updated into database - laravel

i had some problem for updating my data, i was able to catch the file that was going to be updated by using dd and they are there, but when i was submitting the form the data remains the same, nothing change and no error whatsoever, here are my store(update) controller :
public function store(Request $request)
{
//dd($request);
$request->validate([
'attachment_name' => 'required|file|image|mimes:jpeg,png,jpg,gif,svg|max:10048',
]);
$storedImage = $request->attachment_name->store('public/image/');
MediaOrder::updateOrCreate(['id' => $request->id],
[
'nomor'=> $request->nomor,
'nomor_reference'=> $request->nomor_reference,
'periode_start'=> $request->periode_start,
'periode_end'=> $request->periode_end,
'category_id'=> $request->category_id,
'type_id'=> $request->type_id,
'agency_code'=> $request->agency_code,
'agency_name'=> $request->agency_name,
'advertiser_code'=> $request->advertiser_code,
'advertiser_name'=> $request->advertiser_name,
'brand_code'=> $request->brand_code,
'brand_name'=> $request->brand_name,
'nett_budget'=> $request->nett_budget,
'gross_value'=> $request->gross_value,
'nett_cashback'=> $request->nett_cashback,
'nett_bundling'=> $request->nett_bundling,
'version_code'=> $request->version_code,
'spot'=> $request->spot,
'accountexecutive_name'=> $request->accountexecutive_name,
'group_id'=> $request->group_id,
'userto_name'=> $request->userto_name,
'notes'=> $request->notes,
'attachment_name'=> $storedImage,
]);
flash_success_store('Media Order successfully updated.');
if ($request->ajax()) {
return redirect_ajax_notification('media-order.index');
} else {
return redirect_ajax('media-order.index');
}
}
i already find and change it myself but to no avail, maybe someone can have a solution?, thank you for your time.

The most common reason that the model is not updated or entered is that you do not make the attributes fillable in the model itself. Go to your model MediaOrder and check if you have set all attributes fillable.
protected $fillable = [..];

Related

Making Laravel 9 validation rule that is unique on 2 columns

I am trying to update a row in the pages table.
The slug must be unique in the pages table on the slug and app_id field combined.
i.e. there can be multiple slugs entitled 'this-is-my-slug' but they must have unique app_id.
Therefore I have found that formula for the unique rule is:
unique:table,column,except,idColumn,extraColumn,extraColumnValue
I have an update method and getValidationRules method.
public function update($resource,$id,$request){
$app_id=22;
$request->validate(
$this->getValidationRules($id,$app_id)
);
// ...store
}
When I test for just a unique slug the following works:
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> 'required|unique:pages,slug,'.$id
];
}
However, when I try and add the app_id into the validation rules it returns server error.
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> 'required|unique:pages,slug,'.$id.',app_id,'.$app_id
];
}
I have also tried to use the Rule facade, but that also returns server error. Infact I can't even get that working for just the ignore id!
public function getValidationRules($id,$app_id){
return [
'title'=> 'required',
'slug'=> [Rule::unique('pages','slug')->where('app_id',$app_id)->ignore($id)]
];
}
Any help is much appreciated :)
Thanks for the respsonses. It turned out a couple of things were wrong.
Firstly if you want to use the Rule facade for the validation rules, make sure you've included it:
use Illuminate\Validation\Rule;
The other method for defining the validation rule seems to be limited to the following pattern:
unique:table,column,except,idColumn
The blog post that I read that showed you could add additional columns was for laravel 7, so i guess that is no longer the case for laravel 9.
Thanks for your responses and help in the chat!
I recommend you to add your own custom rule.
First run artisan make:rule SlugWithUniqueAppIdRule
This will create new file/class inside App\Rules called SlugWIthUniqueAppRule.php.
Next inside, lets add your custom rule and message when error occured.
public function passes($attribute, $value)
{
// I assume you use model Page for table pages
$app_id = request()->id;
$pageExists = Page::query()
->where('slug', $slug)
->where('app_id', $app_id)
->exists();
return !$pageExists;
}
public function message()
{
return 'The slug must have unique app id.';
}
Than you can use it inside your validation.
return [
'title'=> 'required|string',
'slug' => new SlugWithUniqueAppIdRule(),
];
You can try it again and adjust this custom rule according to your needs.
Bonus:
I recommend to move your form request into separate class.
Run artisan make:request UpdateSlugAppRequest
And check this newly made file in App\Http\Requests.
This request class by default will consists of 2 public methods : authorize() and rules().
Change authorize to return true, or otherwise this route can not be accessed.
Move your rules array from controller into rules().
public function rules()
{
return [
'title'=> 'required|string',
'slug' => new SlugWithUniqueAppIdRule(),
];
}
To use it inside your controller:
public function update(UpdateSlugAppRequest $request, $resource, $id){
// this will return validated inputs in array format
$validated = $request->validated();
// ...store process , move to a ServiceClass
}
This will make your controller a lot slimmer.

Laravel validation couldn't store value after validate and give error 500

I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database.
Here is the code on the controller :
public function update(Request $request, Client $client)
{
$validatedData = Validator::make($request->all(), [
'name' => 'required|max:255',
'logo'=> 'image|file|max:100',
'level' => 'required|max:1'
]);
$validatedData['user_id'] = auth()->user()->id;
if ($validatedData->fails()){
return response()->json($validatedData->errors());
} else {
if($request->file('logo')){
if($request->oldLogo){
Storage::delete($request->oldLogo);
}
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
}
$validateFix = $validatedData->validate();
Client::where('id', $client->id)->update($validateFix);
return response()->json([
'success' => 'Success!'
]);
}
}
It gives error on line :
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
With message :
"Cannot use object of type Illuminate\Validation\Validator as array"
I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.
To retrieve the validated input of a Validator, use the validated() function like so:
$validated = $validator->validated();
Docs:
https://laravel.com/docs/9.x/validation#manually-creating-validators
https://laravel.com/api/9.x/Illuminate/Contracts/Validation/Validator.html
$validatedData is an object of type Illuminate\Validation\Validator.
I would say the error is earlier there as well as this line should give an error also:
$validatedData['user_id'] = auth()->user()->id;
As ericmp said, you first need to retrieve the validateddata to an array and then work with it.

Can't get Livewire Events Emit and Listen to work

I am trying to setup an event listener, so that when a child livewire component gets the title updated, it would refresh the parent component to show the update instead of having to hard refresh the page to see the update.
This is a quick gif showing what is taking place
https://i.gyazo.com/faefb27c2fe0fb32da097fbbf5cc1acb.mp4
I have 2 livewire components.
Parent = ViewSidebar.php / view-sidebar.blade.php
// view-sidebar.blade.php
#foreach ($kanbans as $kanban )
#livewire('kanbans.show-sidebar-kanban', ['kanban'=>$kanban], key($kanban->id))
#endforeach
// ViewSidebar.php
public $kanbans;
protected $listeners = ['refreshKanbans'];
public function refreshKanbans()
{
$this->kanbans = Kanban::where('status', $this->active)
->orderBy('order', 'ASC')
->get();
}
public function mount()
{
$this->refreshKanbans();
}
public function render()
{
return view('livewire.kanbans.view-sidebar');
}
In the child component I set this
public function updateKanban($id)
{
$this->validate([
'title' => 'required',
]);
$id = Kanban::find($id);
if ($id) {
$id->update([
'title' => $this->title,
]);
}
$this->resetInputFields();
$this->emit('refreshKanbans');
}
All of the files are in a subfolder called kanbans could this be breaking it?
Trying to follow along these docs https://laravel-livewire.com/docs/2.x/events
I also tried this approach with calling the emit $this->emit('updateKanbanSidebar'); and setting the listener like this protected $listeners = ['updateKanbanSidebar' => 'refreshKanbans'];
Clearly I am understanding the documentation wrong, but no clue where the issue is.
Any help is much appreciated!
Thank you in advance :)
There is something wrong in your code, so let me help you with. After emit from child (be sure this is doing well) just need have this in parent component
Parent
protected $listeners = ['refreshKanbans' => '$refresh'];
public function render()
{
$this->kanbans = Kanban::where('status', $this->active)
->orderBy('order', 'ASC')
->get();
return view('livewire.kanbans.view-sidebar');
}
Let me know about
I was able to get this to work using this in the child component, and skipping the emits. I was able to DD and the emit was working properly, but not sure why it wasn't updating.
public function updateKanban($id)
{
$this->validate([
'title' => 'required',
]);
$this->kanban->update(['title' => $this->title]);
$this->resetInputFields();
$this->kanban=Kanban::find($this->kanban->id);
}

How can I validate the request user in Laravel?

I am sending a update request like:
Route::put('user/{user}/edit-user-education', 'UpdateUserEducationController#editUserEducation');
My controller is :
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
}
Now how I can validate the request user_id with the user_id already in inserted in DB ? I want to ensure that the only user can update the record who created that one.
How to do so ? Thanks in advance
Check out the docs on validation here:
https://laravel.com/docs/8.x/validation
Specifically, I think you want the exists rule:
https://laravel.com/docs/8.x/validation#rule-exists
The quick and dirty way is to add your validation in the controller but there are some better methods as explained in the docs. I usually opt for Form Requests, which it looks like you've already done as your request is an instance of EditUserEducationRequest.
In the controller you can add:
$validated = $EditUserEducationRequest->validate([
'user_id' => 'required|exists:users',
]);
I assume your user table is called users.
You could alternatively state the exists validation rule for user_id in the rules array of your Form Request as per the docs.
EDIT:
I actually missed a requirement in your original post that is that the user sending the request must be the same user as the one being updated.
That can be handled in the the authorize method of your form request with something like:
public function authorize()
{
return $this->user()->id == $this->user_id;
}
Simply make a check that current user is the same user who is trying to update record.
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
if($user->id==Auth::user()->id){
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
else{
return response()->json([
'error' => 'Invalid User'
]);
}
}
}

Gathering data from multi page form, and adding additional data

So I'm data from a multi-page form, the data is stored like this.
I'm using this tutorial https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->save();
return redirect('/home');
}
That works fine. But how do I add additional data manually using the arrow function? For example, I need to set a status, the ip address, ect. Something like 'status' => 1
Assuming this is the only place you want to add these values to users, you could just add the values after you got it from the session:
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->ip_address = '127.0.0.1';
$user->status = 1;
$user->save();
return redirect('/home');
}
you can add addition data like:
if your $user is laravel object then
$user->setAttribute('status', '1');
or $user if array then
$user['status']=1;

Resources