unexpected result in a query in laravel - database

I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});

pluck will return array if you want to get only single value then use value
// will return array
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
//will return string
$articles=DB::table('users')->where('id','2')->value('name');
// output Sonya Bins
here is an example from the documentation:
if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Read more about it here
Hope it helps.
Thanks

pluck() used to return a String before Laravel 5.1, but now it returns an array.
The alternative for that behavior now is value()
Try this:
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->value('name');
return view('products',compact('articles'));
});

I think it's easier to use the Model + find function + value function.
Route::get('products', function () {
$articles = User::find(2)->value('name');
return view('products',compact('articles'));
});

pluck will return the collection.
I think id is your primary key.
You can just get the first record, and call its attribute's name:
DB::table('users')->where('id','2')->first()->name;
or
DB::table('users')->find(2)->name;

First thing is that you used invalid name for what you pass to view - you don't pass articles but user name.
Second thing is that you use get method to get results instead of first (or find) - you probably expect there is only single user with id = 2.
So to sum up you should use:
$userName = DB::table('users')->find(2)->name;
return view('products',compact('userName'));
Of course above code is for case when you are 100% sure there is user with id = 2 in database. If it might happen there won't be such user, you should use construction like this:
$userName = optional(DB::table('users')->find(2))->name;
($userName will be null if there is no such record)
or
$userName = optional(DB::table('users')->find(2))->name ?? 'No user';
in case you want to use custom string.

Related

Laravel 7: Showing error while passing multiple variable in str_replace

I'm facing error while passing multiple variable in str_replace function.
Error: Argument 1 passed to Xenon\LaravelBDSms\SMS::shoot() must be of the type string, null given, called in
Message Body:
Hello #name#,
Total Amount Purchased : #total#
Previous Due: #previous_due#
Deposit: #deposit#
Total Due: #total_due#
Controller:
$id = 1;
$sms_settings = SmsSetting::findOrFail($id);
if($sms_settings->order_create == 1){
$name = $request->name;
$previous_due = $customer->due;
$deposit = $request->deposit;
$total = $request->total;
$total_due = $request->total_due;
$msgs = $sms_settings->order_create_sms;
$msg = str_replace(array('#name#', '#total#','#previous_due#','#deposit#','#total_due#'), array($name,$previous_due, $deposit, $total, $total_due), $msgs);
$send= SMS::shoot($request->mobile, $msg);
}
Shoot Function:
public function shoot(string $number, string $text)
{
$this->sender->setMobile($number);
$this->sender->setMessage($text);
return $this->sender->send();
}
Here I'm using a Laravel Package for sending SMS to mobile number. How can I pass multiple variable in str_replace?
$request->mobile is null, confirm if you are passing the same in the request. Thats why the error.
Also use $request->validated('mobile'), that is safer.
str_replace seems to be fine. Take a look at Example, but Look at examples again, it might break if characters are overlapping with other arguments
I think the variable $msgs = $sms_settings->order_create_sms; contain empty that's why str_replace couldn't replace the data that you given so
$msg = str_replace(array('#name#', '#total#','#previous_due#','#deposit#','#total_due#'), array($name,$previous_due, $deposit, $total, $total_due), $msgs); , will return null.
I recommend checking $msgs again.
$msgs = $sms_settings->order_create_sms;
Make sure $msgs is not null place is_null($msgs) condition before feeding to str_replace
check more about str_replace: https://www.php.net/manual/en/function.str-replace.php

String Jsonarray in android [duplicate]

So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not

Laravel 5.4 - Array returning NULL instead of a numeric value

Here's a problem that is bothering me for a while.
I have a service provider to pass data to all views, everytime the sidebar is rendered. like this:
`
public function boot()
{
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
view()->share('commondata', $commondata);
View::composer('sidebar', function ($view) {
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
$view->with('commondata', $commondata);
});
}`
Doing a {{ dd($commondata) }} returns the correct values for the menucase arrays, but NULL for the $userrole
If i declare the same $userrole variable in a controller and call the variable in the view, the received data is correct.
Why is this happening?
Thanks in advance
Can't understand what are you actually trying to do.
If you want get user role as array, you can using pluck method:
$userRole = User::where('id', Auth::id())->pluck('role')->toArray();
But for current user you can just get the role
$userRole = [Auth::user()->role];
UPD: you also can do it in view without any sharing
{{ Auth::user()->role }}
If your user has many roles from a different table, and you have the relationship defined, you could do
$userrole = Auth::user()->roles->pluck('name');
//will return all the roles names in an array
//Replace name by the actual column you want from 'roles' table.

How to fetch array value having String Key using Angular

I have an array and want to fetch some values from array which has Strings as key.Please suggest how can i retrieve those values from array have string as key.
Code for Controller is:
var ultColumn=undefined;
$scope.ultColm="Attained Age";
for(var i=0;i<5;i++){
ultColumn=ultrowCellData[i][$scope.ultColmn];//This is not working
}//ultrowCellData contains the array
Please suggest how to get the value of key "Attained Age"
You can use angular.forEach(); For example:
angular.forEach(yourArray, function(value, key){
if(typeof key === 'string'){
console.log("Your result is here :", value);
}
});
Thanks.
If screenshot which you provided shows data included in ultrowCellData then it is not an array but map - var something = ultrowCellData['Attained Age '] will assign value 28 to something
You seem to have forgotten a space at the end of your key, on line 2.
Try Attained Age<space> instead of Attained Age (replace <space> with an actual space).
Notice, though, that this is a non-standard use for an Array, as arrays usually use only numbers as keys.
if at all possible, try using an Object instead.

Wordpress - get_results() - How to know if failed or empty?

I use the Wordpress function $wpdb->get_results()
https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
It says:
"If no matching rows are found, or if there is a database error, the return value will be an empty array."
Then how can I know if the query failed OR if it's empty?
Use
$results=$wpdb->get_results($yoursql);
if (count($results)> 0){
//do here
}
But if you want to know if query failed
$wpdb -> show_errors ();
$wpdb -> get_results ($wpdb -> prepare($sql));
$wpdb -> print_error ();
Bit late to the party here but I'm just looking for the same thing. I've had a browse through the wp-db.php code on version 4.4.2.
On line 1422, inside the method flush() there's a bit of code which resets the last_error property:
$this->last_error = '';
This flush() method is called in the query() method on line 1693:
$this->flush();
The get_results() method calls query() on line 2322:
if ( $query ) {
$this->query( $query );
} else {
return null;
}
With this we can be pretty sure that more or less every time get_results() (Or get_row() too for that matter) is called, query() and flush() are both called, which ensures that last_error is set to the empty string before the query is executed.
So assuming the query runs (If it doesn't, null is returned - if the query is empty for example), last_error should contain an error message if the query was to fail for some reason.
Since last_error is flush()ed/reset each time, it should only contain an error for the last query that was run, rather than the last error for any query that had been run previously. With this in mind it should be safe to rely on last_error to determine whether something went wrong with the query.
$results = $wpdb->get_results($sql);
if (is_null($results) || !empty($wpdb->last_error)) {
// Query was empty or a database error occurred
} else {
// Query succeeded. $results could be an empty array here
}
Not the most intuitive in my opinion, but it seems to be sufficient.
Personally, I've written my own class around wpdb for my own benefit. This is my getResults() method.
public function getResults($query, $bindings = [])
{
// Prepare the statement (My prepare method inspects $query and just returns it if there's no bindings, otherwise it uses $wpdb->prepare()
$prepared = $this->prepare($query, $bindings);
// Execute the statement
$rows = $this->db->get_results($prepared, ARRAY_A);
// If an array was returned and no errors occurred, return the result set
if (is_array($rows) && empty($this->db->last_error)) {
return $rows;
}
// On failure, return false
return false;
}
Hope this helps.
Wpdb->get_results function from wordpress returns the result if successful otherwise it will return null. There can be many reasons if a query get failed.Refer in-depth article on debugging get_results() returning empty results here
Although you can use functions like wpdb->show_error() to check what was the last error after executing the sql query. sometimes this error returns empty
then try to use wpdb->last_query to check the final query that get formed.

Resources