How to check whether there's data from database or not
My DB looks like this
My user Model
public function monsters()
{
return $this->belongsToMany('App\Monster')->orderBy('star');
}
My Controller
public function list_monster_user()
{
//GET USER LOGIN ID
$id = Auth::user()->id;
$monster_user = User::find($id);
//IF DATA IS NOT EMPTY OR USER HAVE MONSTERS
if(!is_null($monster_user->monsters))
{
return 'yes';
}
//IF DATA IS EMPTY OR USER DOESNT HAVE ANY MONSTER
else
{
return 'nope';
}
}
I'm using ajax, so the result will be return to ajax.
I don't get the return I want. I know something's wrong with my if statement.
But I couldn't figure it out.
Since you are not following naming conventions, you should specify all fields in belongsToMany function. Try this:
return $this->belongsToMany('App\Monster', 'karakter_has_monster', 'karakter_id', 'monster_id');
And to check for results, you could use count(). It would be faster.
if($monster_user->monsters()->count() > 0) {
//has monsters
}
Related
I have id(Primary key) of country in multiple tables and I want to check if its value exists or not in another referenced table.
Tried using the below code but I don't think this is the right way. Can anyone please suggest something...
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::select("select count(*) from country where ? not in (?)",[$id,$state]);
if($country == 0)
{
//
}
else{
//
}
}
You can check if a relationship for a record is present (or exists), using exists.
Assuming you have a relationship on your Country model called states:
public function states
{
return $this->hasMany(State::class);
}
You can check if a Country has any States related to it in your database.
// returns true if there are related states, otherwise false
Country::first()->states()->exists();
You can use whatever filtering criteria you want, so rather than first() you could use find($id) or where('field', $value) etc.
Use Exists Method here
public function check($id)
{
$state = State::pluck('country_id');
$country = DB::table('country') //table set
->whereIn('column_name',$state) //if array then used whereIn method
->where('column_name',$id) //if single value use where method
->exists();
if($country)
{
//
}
else{
//
}
}
Within an Eloquent model, I have a scope which I want to return records if the current user has a certain role and nothing if he does not.
I am looking for a way to 'shortcircuit' the query and return an empty array. For now, I have used the following but I feel there must be a better way:
public function scopeForClient($query, User $user)
{
if ($user->hasRole('client')) {
return $query->whereIn('client_id', $user->id);
} else {
return $query->where('id', false);
}
}
I would leave only this part in your scope return $query->whereIn('client_id', $user->id);
//User model
someFilterFunction($query){
if ($user->hasRole('client'))
return $query->forClient();
return [];
}
//Other parts of your application
$result = someFilterFunction($query);
if (!empty($result)) {
// do something with query Builder instance
}
I would avoid doing additional query to database here $query->where('id', false) when there is no need and you know it will return empty result;
I have a table users that has relationship to operations.
\App\user:
public function operation()
{
return $this->belongsTo('App\Operation');
}
So I can do:
$operation = user->operation
Now I want to add a Partition Metric in the Users resource page that tells me the number of users grouped by operation
Right now, it display an id, and it not filtering my users ( need to filter query with company_id )
public function calculate(NovaRequest $request)
{
return $this->count($request, User::class, 'operation_id', 'name');
}
I tried to add name column name, but first it is not working, and second, I would need the name of the operation, not the user, so it should be something like operation.name but it is not working neither.
How can I print the operation name instead of operation_id
PD: Basically, whole process it being more painful because I can't see the output of dump() or dd() in a metric, so I can't debug.
You should use ->label() method as mentioned in Laravel/nova docs:
https://nova.laravel.com/docs/3.0/metrics/defining-metrics.html#customizing-partition-labels.
Then, the correct code should be:
public function calculate(NovaRequest $request)
{
return $this->count($request, User::class, 'operation_id')
->label(function($operationId){
switch($operationId){
case 'opration_1_id': return 'operation_1_name';
break;
case 'opration_2_id': return 'operation_2_name';
break;
default: return 'Other';
}
});
}
On my User model I have the following:
public function isOnline()
{
return $this->hasMany('App\Accounting', 'userid')->select('rtype')->latest('ts');
}
The accounting table has activity records and I'd like this to return the latest value for field 'rtype' for a userid when used.
In my controller I am doing the following:
$builder = App\User::query()
->select(...fields I want...)
->with('isOnline')
->ofType($realm);
return $datatables->eloquent($builder)
->addColumn('info', function ($user) {
return $user->isOnline;
}
})
However I don't get the value of 'rtype' for the users in the table and no errors.
It looks like you're not defining your relationship correctly. Your isOnline method creates a HasMany relation but runs the select method and then the latest method on it, which will end up returning a Builder object.
The correct approach is to only return the HasMany object from your method and it will be treated as a relation.
public function accounts()
{
return $this->hasMany('App\Accounting', 'userid');
}
Then if you want an isOnline helper method in your App\User class you can add one like this:
public function isOnline()
{
// This gives you a collection of \App\Accounting objects
$usersAccounts = $this->accounts;
// Do something with the user's accounts, e.g. grab the last "account"
$lastAccount = $usersAccounts->last();
if ($lastAccount) {
// If we found an account, return the rtype column
return $lastAccount->rtype;
}
// Return something else
return false;
}
Then in your controller you can eager load the relationship:
$users = User::with('accounts')->get(['field_one', 'field_two]);
Then you can do whatever you want with each App\User object, such as calling the isOnline method.
Edit
After some further digging, it seems to be the select on your relationship that is causing the problem. I did a similar thing in one of my own projects and found that no results were returned for my relation. Adding latest seemed to work alright though.
So you should remove the select part at very least in your relation definition. When you only want to retrieve certain fields when eager loading your relation you should be able to specify them when using with like this:
// Should bring back Accounting instances ONLY with rtype field present
User::with('accounts:rtype');
This is the case for Laravel 5.5 at least, I am not sure about previous versions. See here for more information, under the heading labelled Eager Loading Specific Columns
Thanks Jonathon
USER MODEL
public function accounting()
{
return $this->hasMany('App\Accounting', 'userid', 'userid');
}
public function isOnline()
{
$rtype = $this->accounting()
->latest('ts')
->limit(1)
->pluck('rtype')
->first();
if ($rtype == 'Alive') {
return true;
}
return false;
}
CONTROLLER
$builder = App\User::with('accounting:rtype')->ofType($filterRealm);
return $datatables->eloquent($builder)
->addColumn('info', function (App\User $user) {
/*
THIS HAS BEEN SUCCINCTLY TRIMMED TO BE AS RELEVANT AS POSSIBLE.
ARRAY IS USED AS OTHER VALUES ARE ADDED, JUST NOT SHOWN HERE
*/
$info[];
if ($user->isOnline()) {
$info[] = 'Online';
} else {
$info[] = 'Offline';
}
return implode(' ', $info);
})->make();
I have this relationship in one of my model classes:
public function userLike()
{
if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
// RETURN NULL IF RECORD DOESN'T EXIST?
}
As you can see, it checks if the user is logged in and returns the Like record. However, how can I return null if the record doesn't exist?
I tried this:
public function userLike()
{
if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
return null;
}
But I get the error:
local.ERROR: exception
'Symfony\Component\Debug\Exception\FatalErrorException' with message
'Call to a member function addEagerConstraints() on null' in
/var/www/social/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:680
As a side question, am I doing this right? Is this the correct way of doing this or is there a better way?
I'm not sure it is the right way to do this. In your model you should only declare your relationships:
public function userLike()
{
return $this->hasOne('App\Like');
}
And then in a controller or something you go get the like of your user like this:
class LikesController extends Controller {
public function getLike()
{
$like = null;
if (Auth::check()) {
$like = Like::where('user_id', Auth::user()->id)->first();
}
}
}
So we have a getLike() function that get the like of a user from your model Like where the user_id is equal to the authenticated user's id.
Hope it helps!
I'm not sure! But I think it is possible to use count! When it returns 0 you know that there are no records, so you can return null.
You can just use this style in your Like Model :
// return the number of likes
function userLikes()
{
$count = $this->where('user_id', $this->post_id)->count();
// check if not null
return $count ? $count : 0; // if null return 0
}