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';
}
});
}
Related
basically I want to update this table in one go or bulk update.
I wanted to update the "image_id" field on this table.
This is my code in the Controller
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::where('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
but for some reason it doesn't work. if anyone can point out what I missed here it will be great.
thanks
You should use whereIn:
public function storebulk(Request $request, $id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
In Laravel, If you want to update multiple rows or get multiple rows of same type always use whereIn.
The Docs Define whereIn as -
The whereIn method verifies that a given column's value is contained within the given array
public function storebulk(Request $request,$id)
{
$ids= ['8','9','10']; //sent from the front-end
$barcode = Barcode::whereIn('id', $ids)->update(['image_id'=>$id]);
return 'Done';
}
Link to docs
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{
//
}
}
I have the following data model:
(Publication) <-[belongsToMany]-> (Subscriber)
I want to create a Nova Partition Metric to display the number of Subscribers for each Publication.
The calculate method of my Partition class looks like this:
public function calculate(Request $request)
{
return $this->count($request, Subscriber::with('publications'), 'publication.id');
}
But I am getting an "unknown column" error. Anyone know how to make this work?
You could do something like this:
public function calculate(Request $request)
{
$subscribers = Subscriber::withCount('publications')->get();
return $this->result(
$subscribers->flatMap(function ($subscriber) {
return [
$subscriber->name => $subscriber->publications_count
];
})->toArray()
);
}
The count helper only allows to group by a column on model's table. It also don't allow to join tables.
If you want a more complex query, with a join and a group by column in another table, you can build your own array of results and return it with the results helper.
You can see the results helper docs here: https://nova.laravel.com/docs/1.0/metrics/defining-metrics.html#customizing-partition-colors
You should create your array (you can use eloquent or query builder here) inside the calculate function, then return that array with the results helper.
Hope this helps!
You can make the groupBy on publication_foreign_key in Subscriber table and edit the publication_foreign_key to publication_name using ->label() method
Like this
public function calculate(Request $request)
{
return $this->count($request, Subscriber::class, 'publication_id')
->label(function($publicationId)
{
switch($publicationId)
{
case publication_foreign_key_1 : return publication_name_1;
break;
case publication_foreign_key_2 : return publication_name_2;
break;
default: return 'Others';
}
});
}
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
}
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();