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
Related
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);
});
},
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 am trying to call API from ionic but it shows 404 error
here is my code for provider
remoteservice.ts
export class RemoteserviceProvider {
public headers = new Headers( { 'X-API-KEY' :
'xxxxxxxxx' });
public options = new RequestOptions({ headers: this.headers });
constructor(public http: Http) {
console.log('Hello RemoteserviceProvider Provider');
}
rec:any[]=[];
use:any[]=[];
login(credentials) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost/my/v1/adminlogin', credentials,
{headers: this.headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
Login.ts
doLogin() {
this.showLoader();
this.remoteService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.responseData = result;
console.log(this.responseData);
if(this.responseData.message=='Login Success'){
localStorage.setItem('loginData', JSON.stringify(this.responseData));
if(this.responseData.user_type==1){
if(this.responseData.project_type==null){
this.presentToast('You are not assigned to any project');
}
else{
if(this.responseData.project_type=='Concrete'){
console.log(this.responseData.p_id)
this.navCtrl.setRoot(ConcretePage,
{p_id:this.responseData.p_id, s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else if(this.responseData.project_type=='Bricks'){
this.navCtrl.setRoot(ProductionPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else{
this.navCtrl.setRoot(DailyReportPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
}
My API code is laravel
index.php
<?php
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->hook('slim.before.dispatch', function () use ($app){
$headers = request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$api_key = $headers['X-API-KEY'];
// this could be a MYSQL query that parses an API Key table, for example
if($api_key == 'xxxxxxxxxxxxxxx') {
$authorized = true;
} else if ($api_key == NULL) {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key not sent"
}}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
$app->halt(401, $response['message']);
} else {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key invalid" }}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
}
if(!$authorized){ //key is false
// dont return 403 if you request the home page
$req = $_SERVER['REQUEST_URI'];
if ($req != "/") {
$app->halt('403', $response['message']); // or redirect, or
other something
}
}
});
$app->post('/adminlogin', function () use ($app) {
$json = $app->request->getBody();
$input = json_decode($json, true);
$mobile= (int)$input['mobile'];
$password = (string)$input['password'];
$db = new DbOperation();
$response = array();
$response['report'] = array();
if ($db->adminLogin($mobile,$password)) {
$admin = $db->getAdmin($mobile);
$admin1 = $db->getassignedproject($mobile);
$admin2 = $db->getprojecttype($admin1['p_id']);
$admin4 = $db->updateadminlogin($mobile,$password);
$response['error'] = false;
$response['p_id']=$admin1['p_id'];
$response['id'] = $admin['u_id'];
$response['name'] = $admin['username'];
$response['date'] = date('Y-m-d');
$response['user_type'] = $admin['user_type'];
$response['project'] = $admin1['p_name'];
$response['project_type'] = $admin2['p_type'];
$response['location'] = $admin2['location'];
$response['message'] = "Login Success";
} else {
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
echoResponse(200, $response);
});
while am calling API using /adminlogin this shows 404 error
i don't know where i did wrong.
Anyone can please give me some idea to overcome this.
Thanks in Advance
I am developing Custom Component for Joomla.
I did well in validating field by adding custom rule. But if entered value does not pass through my validation, it gives error as "Invalid Field: My Field Name"
I want to replace this with my own message.
I know I can use "JText::_('LANGUAGE_STRING'). But I'm not sure where do I need to add it.
I have custom rule called "validemails" which returns false in client side as well as server side validation.
My Client side Validation is: (components/com_helpdesk/models/forms/create.js)
jQuery(document).ready(function () {
document.formvalidator.setHandler('validemail', function (value) {
var emails = [value];
if (value.indexOf(';') !== -1) {
emails = value.split(';');
}
else if(value.indexOf(',') !== -1) {
emails = value.split(',');
}
regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var result = false;
emails.each(function (value) {
result = regex.test(jQuery.trim(value));
if (result === false) {
return false;
}
});
return result;
});
});
My Server Side Validation is: (components/com_helpdesk/models/rules/validemail.php)
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
return false;
continue;
}
}
return true;
}
}
Please note that I'm developing Front-end view of Component not back-end.
Well fortunately, I got my server side validation working by this way:
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
***$element->addAttribute('message', JText::_('COM_HELPDESK_ERROR_EMAIL').' '.$value);***
return false;
continue;
}
}
return true;
}
}
I got the solution. May be it will be useful for other googlers. Below is a code snippet for client side validation. Put below code in your custom JS:
jQuery('.validate').click(function (e) {
var fields, invalid = [], valid = true, label, error, i, l;
fields = jQuery('form.form-validate').find('input, textarea, select');
if (!document.formvalidator.isValid(jQuery('form'))) {
for (i = 0, l = fields.length; i < l; i++) {
if (document.formvalidator.validate(fields[i]) === false) {
valid = false;
invalid.push(fields[i]);
}
}
// Run custom form validators if present
jQuery.each(document.formvalidator.custom, function (key, validator) {
if (validator.exec() !== true) {
valid = false;
}
});
if (!valid && invalid.length > 0) {
error = {"error": []};
for (i = invalid.length - 1; i >= 0; i--) {
label = jQuery.trim(jQuery(invalid[i]).data("label").text().replace("*", "").toString());
if (label) {
if(label === 'Subject') {
error.error.push('Please Enter Subject');
}
if(label === 'Description') {
error.error.push('Please Enter Description');
}
if(label === 'Priority') {
error.error.push('Please Select Priority');
}
if(label === 'Email CCs') {
error.error.push('Please Enter proper Emails in CC section');
}
if(label === 'Email BCCs') {
error.error.push('Please Enter proper Emails in BCC section');
}
}
}
}
Joomla.renderMessages(error);
}
e.preventDefault();
});
I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}