How to assign value if not increment? laravel - php

I want to assign a value if not exist else increment the value. Below is the one line code that I'm trying to achieve.
session()->put(['validation_count' => session('validation_count')++ ?? 1]);
But I end up this error below.
Can't use function return value in write context
Someone knows the perfect one line solution?

$validationCount = session('validation_count');
session()->put(['validation_count' => ($validationCount ? $validationCount++ : 1]);
Update for comment:
I recommend with variable usage but if you want to one line:
session ()->put ( ['validation_count' => ( session ( 'validation_count' ) ? session ( 'validation_count' ) + 1 : 1 )] );
session ()->save ();

In one line, you can do like so:
session()->put(['validation_count' => (session('validation_count') ? session('validation_count') + 1 : 1)]);

Related

Laravel "undefined array key 0" that is actually defined

This is really weird. Laravel is telling me "undefined array key 0" but I am able to echo the value that Laravel can't seem to see and I can assign it to a variable.
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check[0]->submitted; // <-- $progress_check[0]->submitted contains 1
echo $thing;
exit;
And I get 1 returned from $thing. No errors. But! This:
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check[0]->submitted;
if($thing) {
$do_stages[$do_stage_object->id]['submitted'] = 1;
} else {
$do_stages[$do_stage_object->id]['submitted'] = 0;
}
Gives "Undefined array key 0" on the $thing = ... line that previously threw no error and successfully outputted the value (of 1).
If it helps, here's the print_r and dd of $progress_check:
print_r($progress_check);
Array
(
[0] => stdClass Object
(
[submitted] => 1
[signed_off] => 0
)
)
dd($progress_check);
array:1 [▼
0 => {#644 ▼
+"submitted": "1"
+"signed_off": "0"
}
]
I'm no expert on Laravel or object-oriented PHP (or object-oriented anything else for that matter) so maybe I'm just missing something I should know? Another pair of eyes was equally stumped though so... more eyes please!
I should mention, I'm running Laravel 8.83.22.
Edit: using db::table instead in line with ItsGageH's answer gives the same error and same situation with still being able to echo / assign it (as long as I don't then use if in an if) but slightly different contents in the DB results:
print_r($progress_check);
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[submitted] => 1
[signed_off] => 0
)
)
[escapeWhenCastingToString:protected] =>
)
Edit: bonus points (imaginary points though) if anyone can tell me what that 644 is?
You need to specify the table first, before the Select statement, then use where and get
So, you'd be looking at doing:
DB::table('users_to_stages')
->select('submitted, signed_off')
->where('user_id', '=', Auth::user()->id)
->where('sop_id', '=', $id)
->where('stage_id', '=', $do_stage_object->id)
->get();
Further Laravel select-statement reference here
The answer "Undefined array key 0" means you haven't define any first element with the 0 key. For instance: [0 => Auth::user()->id]
It seems you can workaround the problem without the [0] at $progress_check:
$progress_check = db::select("select submitted, signed_off from users_to_stages where user_id = ? and sop_id = ? and stage_id = ?", [Auth::user()->id, $id, $do_stage_object->id]);
$thing = $progress_check->submitted;
if($thing) {
$do_stages[$do_stage_object->id]['submitted'] = 1;
} else {
$do_stages[$do_stage_object->id]['submitted'] = 0;
}
Your bonus point:
644 is about the permission of reading or writing files, depending of what have been set up with chmod. This choice is often chosen, don't care about it.

How to retrieve the session values in Yii 2

I am facing the problem with Yii 2 session when I add the products to the cart session and fetch session cart values.
session_start();
print_r($_SESSION);
exit;
I got this line.
Array ( [__flash] => Array ( ) [__id] => 65 )
Also while trying Yii 2 way:
$session = Yii::$app->session;
print_r($session);
exit;
I am getting this value:
yii\web\Session Object (
[flashParam] => __flash
[handler] => [_cookieParams:yii\web\Session:private] => Array ( [httponly] => 1 )
[_hasSessionId:yii\web\Session:private] => 1
[_events:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] =>
How to get the session data with keys and values in Yii 2?
Hi Sai you can set or retrieve the session value in yii2 easily by using the following steps
1) To set session value on var 'userVariable'
Yii::$app->session->set('userVariable','1234');
2) For getting the session value of var 'userVariable'
$userVariable = Yii::$app->session->get('userVariable');
you can get session by using $session = Yii::$app->session; hope it will help you :)
First, you need to open session
Yii::$app->session->open();
And you can get all session using $_SESSION
var_dump($_SESSION);exit;
May be useful!
You don't need to start session IF you are using YII2 framework.
Follow these step:
1. $session = Yii::$app->session;
2. $session->set('key', 'value');
3. $session->get('key');
Otherwise directly set value
$session['key']=>'value'
you can get session ID with
Yii::$app->user->id
//OR
Yii::$app->user->identity->id
and you can set new session with
$session = Yii::$app->session;
$session->set('new-name-session', '1234');
check all session with
var_dump($_SESSION);exit;
You need to process Yii::$app->session object in for/foreach loop, like so:
foreach (Yii::$app->session as $key => $value) {
var_dump($value);
}

Non-existent constant return true

Each time user logs in, I extract a serialized array containing rights. When I unserialize the array and try to assign each right to a constant, non-existent constants return TRUE. For instance, here is my call to database :
$req_level = $pdo->prepare('SELECT * FROM users_levels WHERE level_id = ?');
$req_level->execute(array($row['level_id']));
$row_level = $req_level->fetch();
$user_level_name = $row_level['name'];
$permissions = unserialize($row_level['permissions']);
foreach ($permissions as $permission) {
define(strtoupper($permission), 1);
}
$req_level->closeCursor();
My array ($permissions) is :
Array ( [0] => users_read [1] => users_update [2] => customers_read [3] => customers_update )
When I call all possible constants I should get TRUE for those existing and FALSE for those non existing, but here is what I got...
USERS_READ : <?=USERS_READ?> <br/>
USERS_UPDATE : <?=USERS_UPDATE?> <br/>
USERS_CREATE : <?=USERS_CREATE?> <br/>
USERS_DELETE : <?=USERS_DELETE?> <br/>
When I echo constants...
USERS_READ : 1
USERS_UPDATE : 1
USERS_CREATE : USERS_CREATE
USERS_DELETE : USERS_DELETE
So everything returns TRUE in this case.
Any idea ?
Typically, in PHP, constants that are not found are turned into strings with the same name. So, trying to use a constant 'USERS_READ' becomes the string 'USERS_READ' when attempted to be used. The string 'USERS_READ' when converted to boolean will be true.
So, you need to use the method defined in order to check if it exists before trying to evaluate the constant:
http://php.net/manual/en/function.defined.php
Or, you could do something like this:
function userHasPermission( $permission ) {
return constant($permission) === 1;
}
BTW - on a side note, using "dynamic constant" sounds like a design idea you might want to rethink. Constants are usually constant :)

array_filter to check for conditions?

Can i use array_filter to check for specific conditions in a multidimensional array to replace an if() statement?
Want it to replace something like this:
if($item[0] == $key && $item[1] == "Test"){
//do something here....
}else{
//some other code here...
}
Current Array:
Array
(
[Zone] => Array
(
[Type] => s45
[packageA1] => Array
(
[level] => REMOVE FROM DB
[stage] => REMOVE FROM DB
[description] => description goes here
[image] => NULL
)
)
)
I want to search FIRST to see if [Type] exists. If it DOESN'T exist then i think ill use array_splice to insert it into the existing array. If it DOES exist then ill check if [packageA1] exists, if [packageA1] DOESN'T exist then i'll use array_splice once again. If [packageA1] DOES exist then ill skip over any type if inserting..
Does that make sense?
array_filter is designed for filtering arrays, not replacing boolean logic based on the contents of arrays.
array_filter takes 2 parameters - input and callback.
The callback function should take a single parameter (an item from the array) and return either true or false. The function returns an array with all of the items which returned false removed.
(If no callback function is specified, all items equal to false will be removed from the resulting array.)
Edit:
Based on your updated text, the below code should do what you want:
if (!$item['Zone']['Type']) {
$item['Zone']['Type'] = $something;
}
if (!$item['Zone']['packageA1']) {
!$item['Zone']['packageA1'] = $something;
}
Obviously you need to replace $something with what you actually want to add.
This code could be shortened by the use of ternary operators.
If you are running PHP 5.3 or greater you can do the following:
$item['Zone']['Type'] = $item['Zone']['Type'] ?: $something;
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ?: $something;
Prior to 5.3 you cannot miss out the middle of a ternary operation and have to use the full format as follows:
$value = conditon ? if_true : if_false;
(When using ?: as in my example, 'condition' and 'if_true' take the same value.)
The full ternary operator (for PHP prior to 5.3) would look like:
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ? $item['Zone']['packageA1'] : $something;

PHP - warning - Undefined property: stdClass - fix? [duplicate]

This question already has answers here:
PHP check whether property exists in object or class
(10 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I get this warning in my error logs and wanted to know how to correct this issues in my code.
Warning:
PHP Notice: Undefined property: stdClass::$records in script.php on line 440
Some Code:
// Parse object to get account id's
// The response doesn't have the records attribute sometimes.
$role_arr = getRole($response->records); // Line 440
Response if records exists
stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => User
[Id] =>
[any] => stdClass Object
(
[type] => My Role
[Id] =>
[any] => <sf:Name>My Name</sf:Name>
)
)
)
[size] => 1
)
Response if records does not exist
stdClass Object
(
[done] => 1
[queryLocator] =>
[size] => 0
)
I was thinking something like array_key_exists() functionality but for objects, anything? or am I going about this the wrong way?
if(isset($response->records))
print "we've got records!";
isset() is fine for top level, but empty() is much more useful to find whether nested values are set. Eg:
if(isset($json['foo'] && isset($json['foo']['bar'])) {
$value = $json['foo']['bar']
}
Or:
if (!empty($json['foo']['bar']) {
$value = $json['foo']['bar']
}
In this case, I would use:
if (!empty($response->records)) {
// do something
}
You won't get any ugly notices if the property doesn't exist, and you'll know you've actually got some records to work with, ie. $response->records is not an empty array, NULL, FALSE, or any other empty values.
You can use property_exists
http://www.php.net/manual/en/function.property-exists.php
If you want to use property_exists, you'll need to get the name of the class with get_class()
In this case it would be :
if( property_exists( get_class($response), 'records' ) ){
$role_arr = getRole($response->records);
}
else
{
...
}
Error control operator
In case the warning is expected you can use the error control operator # to suppress thrown messages.
$role_arr = getRole(#$response->records);
While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using # may be useful is when creating an object from user input and running it through a validation method before using it in further logic.
Null Coalesce Operator
Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.
$role_arr = getRole($response->records ?? null);
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.

Categories