I have a simple database query to put out some stuff from database like example:
$user->HeadHits = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->select("cs.h_1")
->first()->h_1;
And blade:
#if ($user->HeadHits == 0)
0%
#else
<?php echo number_format($user->HeadHits / $user->AllHits * 100,2); ?>%
#endif
But i'm getting error if user steam_id not find in database:
Trying to get property of non-object
Any suggest? Thanks
This is because when you use DB (Query Builder) and first it will return null if the row can not be found.
You would need to add a check in to see if the value exists:
$cs = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->select("cs.h_1")
->first();
$user->HeadHits = $cs ? $cs->h_1 : 0;
A shorter approach would be to use value():
$user->HeadHits = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->value('h_1') ?: 0;
Lastly, just a FYI but you don't need to be explicit with adding the table alias before the column name since you're only querying one table. Also, you don't need to add = with where() as it will assume this is the operator that should be used. Ultimately, you can reduce your code to something like:
$user->HeadHits = DB::table('csstats')->where('steamid', $user->steam_id)->value('h_1') ?: 0;
you can check that with isset()
like that
if(isset($user->HeadHits ) )
Related
Currently, I have tbl_projtask from MySQL
and I have this query in my laravel app. This works fine if the tbl_projtask has rows.
$projtask = DB::connection('mysql')->select("SELECT * from tbl_projtask WHERE projCode = '".$request->projCode."' AND taskCode = '".$request->taskCode."' AND deleted = 0")
But when I truncate the table.
This query returns me an error like this
"message": "Undefined offset: 0",
I'm using count() to validated if there's data inside the table.
something like this
if(count($projtask)){
//Some codes
}else{
//Some codes
}
If I truncate the table. The code gives me the error stated above. But if not truncated and has some rows. The code of count() is working fines. What is the best approach for this?
Since your are comparing to the integer count of the table data.
Change condition to something like this.
if(count($projtask) > 0){
//Some codes
}else{
//Some codes
}
Also you can use query builder.
$projtask = DB::table('tbl_projtask')
->select("*")
->where(['projCode' => $request->projCode, 'taskCode'=> $request->taskCode, 'deleted' => 0 ])
->get()
I think your missing either ->get() or ->first(), if you choose get() this will give you an expected return of populated or empty collection, ie:
$projtask = DB::connection('mysql')->select("SELECT * from tbl_projtask WHERE projCode = '".$request->projCode."' AND taskCode = '".$request->taskCode."' AND deleted = 0")->get()
so by doing so you can now check if it is empty or not, ie:
if(empty($projtask) === true){
// Handle logic if the collection is empty here
}
// else return the $projtask
return $projtask;
I have some problems here.
I get a collection which like:
$VenderData=Vender::where('active', '=', '1')->get();
Inside the collection i have a column called 'type' and the data looks like 'A1,A2,A3,'
or
'A1,A3,'
I want to transfer those codes to real names from
another table 'vender_type'.
code name
A1 XX
A2 OO
A3 ZZ
then add a new column into the original collection $VenderData.
How can i do this?
You must split the type attribute (using array explode(string $delimiter , string $string)) , and get the name of each one from vender_type table, try this :
$VenderData = Vender::where('active', '=', '1')->get();
foreach($VenderData as $vend)
{
$vend->new_type = array();
$types = explode(",", $vend->type);
foreach($types as $type)
{
$t = vender_type::where('code', $type)->first();
if($t)
$vend->name_type[] = $t->name;
// or for example : $vend->name_type[$type] = $t->name;
}
}
I hope that will help you.
I think that you need better query than modifying each value after. This vender_type is probably some foreign key in you database so you can get that value in query builder. To find out about foreign keys and joins in laravel eloquent check this.
Basically you need something like this
$users = DB::table('table1')
->join('table2', 'table1.vender_type', '=', 'table2.vender_type')
->select('table1.code', 'table1.name', 'table2.vender_type')
->where('table1.active', '=', '1')
->get();
Just replace table1 and table2 with values of you table names in database and you're done.
Hope it helps
I know to check how to fetch a particular item in laravel like
$PackCount = PackModel::where('PackId', Input::get('packid'))->count();
But how can i check whether the items are matches another two coloumn i.e.,
where condition for IsActive and IsAvailable ?
If you want to have more where in your Query then just do
$PackCount = PackModel::where('PackId', Input::get('packid'))->where('IsActive', '=', '1')->where('IsAvailable', '=', '1')->count();
Read more about Advance Where here
Try this..
$count = PackModel::where('PackId', Input::get('packid'))->where('IsActive', '1')->where('IsAvailable', '1')->count();
I have a problem that I can't fix :
this request works in PHPMYADMIN
SELECT cronState.name, command.name, parameter.keyword, eventParameterValue.value
FROM cronState, commandInstance, command, eventParameterValue, parameter
WHERE cronState.id = commandInstance.cronState_id
AND commandInstance.command_id = command.id
AND eventParameterValue.commandInstance_id = commandInstance.id
AND eventParameterValue.parameter_id = parameter.id
AND cronState.id =32
it returns :
name name keyword value
on20 DigitalPinSet State 1
on20 PwmPinSet DutyCycle 20
and it's ALL I want.
LITTLE EDIT : I use an AJAX Request(with a state_name) to this method which should returns the query result.
Now, when I try to implement it with the Laravel Query Builder, it returns some errors.
My code:
$cronState_id = DB::table('cronState')
->where('name', Input::get('state_name'))
->first();
$cronEvent = DB::table('cronState')
->join('commandInstance', 'commandInstance.cronState_id', '=', 'cronState.id')
->join('command', 'commandInstance.command_id', '=', 'command.id')
->join('eventParameterValue', 'eventParameterValue.commandInstance_id', '=', 'commandInstance.id')
->join('eventParameterValue', 'eventParameterValue.parameter_id', '=', 'parameter.id')
->where('cronState.id', '=', $cronState_id->id)
->select('cronState.name', 'command.name', 'parameter.keyword', 'eventParameterValue.value');
foreach($cronEvent as $result){
$ev = $result['keyword'];
}
return $ev;
The error for this code :
{"error":{"type":"ErrorException","message":"Undefined index:
keyword","file":"/var/www/stage/app/controllers/EventController.php","line":48}}
if I change
foreach($cronEvent as $result){
$ev = $result['keyword'];
}
return $ev;
to
return $cronEvent;
(just delete the foreach loop and rename the returning variable), I have this error :
{"error":{"type":"ErrorException","message":"Object of class
Illuminate\Database\Query\Builder could not be converted to
string","file":"/var/www/stage/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Response.php","line":361}}
So, how can access to my data in the object ? Maybe my Query Builder implementation doesn't works...
Thanks for any help !
There is missing get() at the end of that query builder, thus you don't run the query at all. That's it.
I am finding that I often need to select a field, based on a condition other than the id.
So, $user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get(); works perfectly.
That is until you set one of the where's to allow nulls (let's do last_login).
That is, it can either have a value or be null.
That means you need to use one of two function where() or whereNull() and to do that you need to break the chain, so it becomes
$user = User::where('last_warning', $lastWarning);
is_null($lastLogin) ? $user->whereNull('last_login') : $user->where('last_login', $lastLogin);
$user = $user->get();
I am wondering if where has a way to deal with this? as currently if you pass null through to where you get where column = null which doesn't work!
Two options:
Option 1:
if (is_null($lastLogin))
{
$user = User::whereNull('last_login')->where('last_warning', $lastWarning)->get();
}
else
{
$user = User::where('last_login', $lastLogin)->where('last_warning', $lastWarning)->get();
}
Option 2:
$user = User::where('last_login', (is_null($lastLogin) ? 'IS' : '=') ,$lastLogin)->where('last_warning', $lastWarning)->get();
Option two makes the query 'where last_login = x' or 'where last_login IS null'
You can try this:
User::where(function($query) use ($lastlogin)
{
if(is_null($lastLogin))
{
$query->whereNull('last_login');
}
else
{
$query->where('last_login', '=', $lastLogin);
}
})->get();
It is a good solution when dealing with long queries with more than one parameter.
You can use DB::raw() as well:
User::where('last_login', 'IS', DB::raw('null'))->where_last_warning($lastWarning)->get();
As of Laravel 5.3 you are now able to ->where('column', null) to automatically produce WHERE column IS NULL.
If using variable, make sure that they have PHP null strict value.