Im doing my first CRUD with Vue - Laravel, i did a Add function that works fine but my Edit button is doing another Add function.
(I get the alert from updateDespesa alert("Usuário Alterado!");)
My Frontend:
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
des: this.despesa.des,
valr: this.despesa.valr,
vencc: this.despesa.vencc,
stt: this.despesa.stt,
emiss: this.despesa.emiss,
})
.then((response) => {
this.despesa.id = "";
this.despesa.valr = "";
this.despesa.stt = "";
this.despesa.vencc = "";
this.despesa.emiss = "";
this.getDespesa();
if(despesa){
alert("Usuário Alterado!");
}
})
.catch((err) => {
console.log(err);
});
},
My Backend:
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
In your backend, try update this and see
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
and also please check the Despesa Model has declared the input fields in protected $fillable
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
...
})
.then((response) => {
// add this line, to check only alert when id is not null
// so that it only alert when update
if(despesa){
alert("Usuário Alterado!");
}
....
})
.catch((err) => {
console.log(err);
});
},
Related
I need to make dynamic form in symfony 5 with ajax.
I make post request with axios on input value change on main route "/".
This route call my controller and i call dump() function for debug my request but i don't have any params on my request.
I looked in my network and my data is posted well. But I don't receive params on my request controller :/
On my view
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>
<script>
cat = document.getElementById("article_category")
token = document.querySelector("#article__token");
title = document.querySelector("#article_title");
cat.addEventListener("change", function (e) {
let form = document.querySelector("form")
let data = {}
data[title.getAttribute("name")] = title.value
data[token.getAttribute("name")] = token.value
data[cat.getAttribute("name")] = cat.value
axios.post("https://127.0.0.1:8000/", data).then(res => {
str = res.data
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html')
console.log(doc);
}).catch(function (error) {
console.log(error);
});
})
</script>
My Controller
/**
* #Route("/", name="article")
*/
public function index(Request $request, EntityManagerInterface $em): Response
{
$article = new Article();
$form = $this->createForm(ArticleType::class, $article);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
dump($request);
}
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($article);
$em->flush();
}
return $this->render('article/index.html.twig', [
"form" => $form->createView(),
]);
}
FormType
$builder
->add('title')
->add('category')
->add('Submit', SubmitType::class);
$builder->get('category')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$form = $event->getForm();
if ($form->getData()->getName() == "Cat 0") {
$form->getParent()->add('tag', EntityType::class, [
'class' => Tag::class,
]);
}
}
);
i'm writing a code using laravel as backend and vue-cli as frontend.
i've got a problem with the data to send to an API laravel restful controller. I get back as answer the err 500.
That's my saveEvent code:
saveEvent() {
const staff = this.$store.getters.get_selected_staff.map(
raw_staff => {
return {
...raw_staff,
icon: "mdi-drama-masks" ? "actor" : "technician",
percent:
raw_staff.percent == "full"
? 1
: eval(raw_staff.percent),
allowance: parseInt(raw_staff.allowance),
daily: parseInt(raw_staff.daily)
};
}
);
const show = {
...this.$store.getters.get_tournee_show_detail
};
this.$http
.post(
"http://localhost:8080/api/tourneeDetail",
`show=${JSON.stringify(show)}&staff=${JSON.stringify(
staff
)}`
)
.then(response => {
this.closeEvent();
})
.catch(error => {
console.log("errore nella registrazione", error);
});
// );
}
The datas goest straight to the controller and get manages in this way:
public function store(Request $request)
{
//
dd($request->all());
$tournee = new TourneeDetail;
$show = json_decode($request->show, true);
$staff = json_decode($request->staff, true);
foreach ($show as $detail => $value){
if($detail == "stage_id"){
$tournee->stage_id = $value['id'];
}
else{
$tournee[$detail] = $value;
}
}
$tournee->save();
foreach ($staff as $row){
$staff = new Staff;
foreach ($row as $detail => $value){
if ($detail!="icon" && $detail!="names" ){
$staff[$detail] = $value;
}
}
$staff->type = $row["icon"];
$staff->tournee_detail_id = $tournee->id;
$staff->save();
foreach ($row["names"] as $id){
$staff_person = new StaffPerson;
$staff_person->person_id = $id;
$staff_person->staff_id = $staff->id;
$staff_person->save();
}
}
return $tournee;
}
The problem is that i get the 500 error on the 1rst foreach. I put a dd to check the $request->all() and i noticed that the payload sent is correct but the preview is an empty array!
I dunno how to fix this problem..any help would be appreciated!
Thank you
Valerio
I want to check record is_featured is a column name if any product is is_featured 1 is already exist error message should be shown Trying to assign an already assigned featured
how can i do that please help me thanks.
https://ibb.co/1Zv2KBW
controller
public function featured(Request $request)
{
if ($request->id) {
$featured = $request->input('is_featured');
$assignFeature = Product::where('is_featured', '=', $featured)->first();
if ($assignFeature) {
abort(405, 'Trying to assign an already assigned featured');
}
} else {
$response['is_featured'] = false;
$response['message'] = 'Oops! Something went wrong.';
$id = $request->input('id');
$featured = $request->input('is_featured');
$featureditem = Product::find($id);
if ($featureditem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
return response()->json($response, 409);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
remove this abort()
if ($assignFeature) {
//abort(405, 'Trying to assign an already assigned featured'); //remove this
$response['is_featured'] = false;
$response['message'] = 'Trying to assign an already assigned featured.';
return response()->json($response, 200);
}
Try this:
$product_created_status = $product->wasRecentlyCreated ? 1 : 0 ;
if product is already created it returns 0, else returns 1
I'm using XMLHttpRequest to avoid using JQuery and I wanna make an Ajax request to delete an object but I keep getting redirected back and getting FOUND (302) HTTP errors.
This is my code:
function deleteGuia(urlToSend) {
var borra = confirm('¿Está seguro de borrar la guía?');
if (!borra) {
return;
}
var req = new XMLHttpRequest();
var csrfToken = document.querySelector('meta[name="csrf-token"]').content;
req.open("POST", urlToSend, true);
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
if (req.status != 200) {
var msg = JSON.parse(req.response);
alert(msg.error);
} else {
alert('Exitoso');
}
}
}
var data = new FormData();
var guia = "{{$guia ?? ''}}";
var estado = "{{$tipo ?? ''}}";
data.append("guia", guia);
data.append("tipo", estado);
req.send(data);
}
</script>
This one's the controller function:
public function eliminarGuia(Request $request) {
$request->validate([
'guia' => 'required|numeric',
'tipo' => 'required'
]);
$guia = (int)$request->input('guia');
$tipo = $request->input('tipo');
\Log::info('Guia' . $guia . ' Tipo: '. $tipo);
if (strtoupper($tipo) === 'ENTREGA'){
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$borra_ciclos = Device::where('guia_recepcion', $guia)->delete();
if(!$borra_guia) {
return response(400)->json(['error', 'La guía no se encontró.']);
}
} else if (strtoupper($tipo) === 'REVERSA') {
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$devices = Device::where('guia_reversa', $guia)->get();
if (!$borra_guia){
return response(400)->json(['error', 'La guía no se encontró.']);
}
foreach($devices as $device)
{
if (!$device->fecha_recepcion) {
$device->delete();
} else {
$device->guia_reversa = 0;
$device->fecha_reversa = null;
$device->save();
}
}
} else {
return response(400)->json(['error', 'La guía no se encontró.']);
}
return response(200);
}
web.php
Route::post('borrar_guia', 'VistasController#eliminarGuia')->name('borrar_guia');
There's no redirection at all. Why might that be happening? I don't know what else to add. The controller should return a 200 code when it delets an existing object in the database but it's getting a 200 from the redirection.
I'm working with laravel and native ajax. I am wondering where do I put diffForhHumans() when using ajax. In my Controller. I just return the object fetch.
Here's my Controller
public function getDownlines($id) {
$upline = Upline::find($id);
return $upline->downlines;
}
Model
public function downlines() {
return $this->hasMany('App\Downline');
}
HTML Code in View
<div id="downlines">
<div class="downlines-title-container">
<p class="title"></p>
</div>
<div id="downlines-holder">
<div class="p_parent_header">
<p>ID</p>
<p>Account Code</p>
<p>Created By</p>
<p>Created At</p>
</div>
</div>
</div>
Script in Ajax
var downlines = document.getElementById('downlines'),
downlines_holder = document.getElementById('downlines-holder');
function getPromise(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(xhr.status == 200) {
resolve(xhr.response);
} else {
reject(Error(xhr.statusText))
}
}
xhr.onerror = function() {
reject(Error('Network Error'));
};
xhr.send();
})
}
function getDownlines(e, id) {
getPromise('upline/getdownlines/' + id).then(function(response) {
var resp = JSON.parse(response),
p_parent = document.getElementsByClassName('p_parent'),
p = p_parent.length;
while(p--) p_parent[p].remove();
if(resp.length > 0) {
downlines.style.display = 'initial'
downlines.children[0].children[0].innerHTML = e.innerHTML;
for(var i = 0; i < resp.length; i++) {
var p_parent = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p'),
p3 = document.createElement('p'),
p4 = document.createElement('p');
p_parent.classList.add('p_parent');
p1.innerHTML = resp[i].id;
p2.innerHTML = resp[i].account_code;
p3.innerHTML = resp[i].created_by;
p4.innerHTML = resp[i].updated_at;
p_parent.appendChild(p1);
p_parent.appendChild(p2);
p_parent.appendChild(p3);
p_parent.appendChild(p4);
downlines_holder.appendChild(p_parent);
}
} else {
downlines.style.display = 'none'
}
}, function(error) {
console.log(error);
})
}
I'm searching for the same problem and doesn't find one.
Any help would be appreciated. Thanks!!!
Please do this before returning the downlines
public function getDownlines($id)
{
$upline = Upline::find($id);
return $upline->downlines->map(function($downline) {
return [
'id' => $downline->id,
'account_code' => $downline->account_code,
'created_by' => $downline->created_by,
'created_at' => $downline->created_at->diffForHumans(),
'updated_at' => $downline->updated_at->diffForHumans(),
];
});
}
I am unsure if you want to use created_at or updated_at, because in the html you have written <p>Created At</p> but in the AJAX request, you have written p4.innerHTML = resp[i].updated_at;. So I added both in the return array :)