This is my code:
public function getLists(Request $request)
{
$user = $request->user()->id;
$apikey = DB::table('apikey')->where('api_key', '=', $user);
if($apikey){
$mc = new MailChimp($apikey);
$mailchimp_ping = $mc->get('lists',['fields' =>
'lists.id,lists.name']);
return Response::json($mailchimp_ping, 200);
}
else
{
$errorResponse = [
'message' => 'Lists not found!',
'error' => '401'
];
return Response::json( $errorResponse);
}
}
I am trying to get mailchimp list based on logged in user id where i am doing wrong? is my where clause expects something else?
Any help would be highly appreciated!
Use the value() method to execute the query and get the key. For example, if a column with key is called apikey:
$apikey = DB::table('apikey')->where('api_key', $user)->value('apikey');
In my case this error came up when changed this:
Route::view('/report', '/main_pages/orders_parts/report')->name('guzorishi_order_1');
to
Route::get('/report/{order_id}', function ($order_id) {... })->name('guzorishi_order_1');
but forgot Route::view one
rename to Route::get
Related
I am new at PHP. We are creating REST API in Phalcon and I've created a put request. It already works, but I would like to check if update has really happened before sending a success response. So I've created a conditional for that ( if (!$product->update()) ), but it always returns 'true'. How can I check if any field has changed in a record?
public function put()
{
$id = $this->getParam('id');
$input = $this->getRawData();
$product = Product::findFirst([
'conditions' => 'id = :id:',
'bind' => ['id' => $id]
]);
if ($product === null){
throw new NotFoundException();
}
$product->assign($input);
$product->update();
if (!$product->update()) {
$this->errorResponse($product->getMessages());
} else {
$this->successResponse($product->toArray($product->update()));
}
}
You can use Model Events, i.e. afterUpdate and notSaved, like:
use Phalcon\Mvc\Model;
use Phalcon\Http\Response;
class ModelBase extends Model
{
public function afterUpdate()
{
$response = new Response();
$response->setJsonContent([
'success' => true,
'message' => "Record updated"
])->send();
}
public function notSaved()
{
$response = new Response();
$response->setJsonContent([
'success' => false,
'message' => 'Record not saved'
])->send();
}
}
The Product and all other models will extend ModelBase. Then your code could be:
public function put()
{
$id = $this->getParam('id');
$input = $this->getRawData();
$product = Product::findFirst([
'conditions' => 'id = :id:',
'bind' => ['id' => $id]
]);
if ($product === null){
throw new NotFoundException();
}
$product->assign($input);
$product->update();
}
And Phalcon event will respond if the model was updated or not. If you prefer, you can also use custom http response codes for update or notSaved. More information about Model Events in the documentation
You are calling $product->update() three times. You do it once after the assign, then again for your if test, which is why it's always returning TRUE there I believe, and once inside the toArray() which may not actually return anything since the second and third updates don't have any data to update (not sure about that though).
I would code this as follows:
$product->assign($input);
$results = $product->update();
if (!results) {
$this->errorResponse($product->getMessages());
} else {
$this->successResponse($results->toArray());
}
I am assuming that the $product->assign($input); statement is working as expected to update the $product data for you. I don't use that. I prefer to do direct assignments for updates so nothing is left to chance, ie. $product->whatever = $input['whatever'];.
Give this a try and hopefully it will work as expected for you.
I am new in PHP and working to modify one API. Its built with Laravel Framework. I have API function like below in my controller.
public function DeleteOneMail(Request $request)
{
$uid = $request->uid;
if (\Request::is('api/*')) {
if ($request->has('key')) {
if (in_array($request->input('key'), explode(',', env('API_KEY')))) {
if ($uid == '') {
return response()->make('Please Enter UID', 401);
} else {
$client = Client::account('default');
$client->connect();
$inbox = $client->getFolder('INBOX');
$message = $inbox->getMessage($uid);
if ($message) {
return response(['success' => 1], 200);
} else {
return response(['success' => 0, 'message' => 'No Data Found'], 200);
}
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
} else {
return response()->make('Unauthorized Access. Please enter correct API Key', 401);
}
}
}
I am calling API like below
https://example.com/api/delete-one-mail?key=2221212&uid=214
Its working fine without any issue. Now I want pass multiple uid with request and so I can process that uid one by one with my api function. I am not getting idea how I can pass arrary and process it. Let me know if any expert can help me for solve my puzzle. Thanks!
Your can pass an array like this
https://example.com/api/delete-one-mail?key=2221212&uid[]=214&uid[]=111&uid[]=222
$request->uid should be an array but you can make sure (if anyone use the old url with ony one uid) by doing
$uids = Arr::wrap($request->uid);
If you want to send an array by GET request just use []
https://example.com/api/delete-one-mail?key=2221212&uid[]=1&uid[]=2
In your controller you will get an array
$uid = $request->uid;
dd($uid);
As a result you will get
[1, 2]
I want check if my form value equals in database value in laravel
Here is my controller class
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id , 'sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
What i do wrong?
update to
DB::table('users')->where(['id',$id ])->where([ 'sms_token_in'
,$sms_token])->update(['sms_verify'=>'1' ]);
The most simple way to use where is
two parameters, 1: database field name, 2: value
three parameters (field name, operator, value) ('1', '>=', 3)
DB::table('users')->where('id',$id)->where('sms_token_in', $sms_token)->update([
'sms_verify'=>'1'
]);
Try
DB::table('users')->where([
['id',$id],
['sms_token_in', $sms_token]
])->update([
'sms_verify'=>'1'
]);
First you must accept two parameter from your function. Look like only you are passing only one.
change function parameter to
public function code_post(Request $request, $id = 0)
then
if(!empty($id)){
User::where(['id' => $id,'sms_token_in' => $sms_token])->update([
'sms_verify'=>'1'
]);
}
// you can do this in two way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id)->where('sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
//2nd way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where(['id',$id , 'sms_token_in' ,$sms_token])->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
The best whey to do it is on Validators in laravel so, if it don't exist create a classe validator that extends "LaravelValidator" and do it:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'sms_token_in' => 'required|unique:your_table_name',
],
ValidatorInterface::RULE_UPDATE => [],
]; protected $messages = [
'sms_token_in.unique' => 'Your duplicate message!'
];
In your controller instantiate your validator in construct like it:
public function __construct(MyValidatorClass $validator)
{
$this->validator = $validator;
}
And in your controller function store do it, before your persist on database.
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
In this way, you can use validator from Laravel to check and return anything you want to your user.
function check(Request $request){
//validate
$request->validate([
'email'=>'required|email',
'user_pass'=>'required|min:5|max:12'
]);
$userInfo=Employee::where('email','=',$request->email)->first();
if(!$userInfo){
return back()->with('fail','We do not recognize your email address');
}else{
//check password
if($request->user_pass=$userInfo->user_pass){
$request->session()->put('LoggedUser', $userInfo->emp_id);
return redirect('/employee/dashboard');
}else{
return back()->with('fail','Incorrect password');
}
}
}
In this method im check if the user_pass from request is equal to $userInfo->user_pass that query from database.
if($request->user_pass=$userInfo->user_pass)
I am tring to make test for my project, could someone show me example how to write tests or give me some good video course to learn testing.
In my example I am tring to test this part:
public function getProjectsForUser(){
if(Auth::user() -> admin_id == NULL){
$this->id = Auth::user() -> id;
}else{
$this->id = Auth::user() -> admin_id;
}
$projects = User::findOrFail(Auth::user() -> id)->projects()->where('admin_id', '=', $this->id)->get();
$role = User::findOrFail(Auth::user() -> id)->roles;
$users = User::where('admin_id', '=', $this->id)->lists('name','id');
return array('projects' => $projects,'users' => $users,'roles' => $role );
}
It was my model Project.php
Here is my PorojectController:
public function project(Project $projects){
$this -> projects = $projects ->getProjectsForUser();
return view('projects',$this -> projects);
}
Here is my test to check if user logged...
public function testHome()
{
$this->be(User::find(1));
$response = $this->call('GET', '/projects');
//CHECK IF AUTH USER
$this->assertTrue($response->isOk());
}
Now I need to check if I get right values inside array, for $project, $role, $users.
You can use assertViewHas() to assert values that should have been passed to the view. For example:
public function testHome(){
$this->be(User::find(1));
$response = $this->call('GET', '/projects');
//CHECK IF AUTH USER
$this->assertTrue($response->isOk());
$this->assertViewHas('projects', 'expected value for projects');
$this->assertViewHas('users', 'expected value for users');
$this->assertViewHas('roles', 'expected value for roles');
}
By the way: If you pass no second argument the method will just assert that the variable exists but won't compare the value.
To accomplish the same with a bit a different syntax you can use assertViewHasAll() and pass everything as array:
$this->assertViewHasAll([
'projects' => 'expected value for projects',
'users' => 'expected value for users',
'roles' => 'expected value for roles'
]);
I have problem with Yii. I have following code in controller:
...
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
...
And Im getting this error:
Call to undefined method stdClass::save()
What's wrong?
oo i see you need to test if you have a user
just do :
if($user)
is your model extand a CactiveRecord ?
you should display the errors to know what's wrong
if(!$user->save()){
var_dump($user->getErrors());
}
this will be helpfull
Your error is to classic to knwo exactly what went wrong! here's a problem that could be the reason of your error:
When you find your user, if it doesn't find it the method will return false then the rest of the operations will fail. You should perform something like:
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
if($user !== null) {
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
}
if ($model->load(Yii::$app->request->post())) {
$model->startDate = $modifiedStartDate;
$model->timeFrom = $modifiedFromTime;
$model->timeTo = $modifiedToTime;
//echo '<pre>';
//print_r($model);exit;
$model->save();
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['timelog/index']);
} else {
return $this->render('create',
[
'model' => $model,
]);
}
//why the error occurs while using the $method->save(); function.