Laravel merge a relation - laravel

How can I merge my Laravel code to have only one collection? I have the following
$users = User::with(['messages'=> function($query) {
$query->select('sender');
}])->with(['files' => function($query) {
$query->select('size');
}])->get(['name']);
I expect my results to be
[
{
"name": "user 1",
"sender": "user 3",
"size": "3 MB"
}
]

You wrote messages and files as plural mean its a OneToMany, mean messages and files should retrieve a collection of object
Anyway if its for an API (as i see you want to return json) you could use the laravel ressources (https://laravel.com/docs/5.7/eloquent-resources) and prepare your object
return [
'name' => $this->name,
'sender' => $this->messages->sender,
'size' => $this->files->size
]

When you are using with() relation, the resultant collection will have the relative collections inside it.
In your case :
user_collection
- userdata
.
.
- file_collection
- message_collection
Now, there are few ways you can do it :
1. Have a join query :
$users = User::join('messages', 'messaged.user_id', '=', 'users.id')
->join('files', 'files.user_id', '=', 'users.id')
->select('users.name', 'files.size', 'messages.sender')
->get();
2. Format data using resources :
Resources are a kind of mapper or modifier which will return the response in format you like. It standardises the response the way you want it.
You can create app\Http\Resources\UserResource.php:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'size' => $this->files->size,
'sender' => $this->messages->sender,
'name' => $this->name
];
}
}
And then inside controller :
return new UserResource(User::find(1));
The advantage is that if you want messages to look certain way, you can nest the Resource classes. The documentation has detailed examples.

Related

Laravel - Get array with relationship

I have an ajax call that returns an array:
$reports = Report::where('submission_id', $submissionID)
->where('status', 'pending')
->get(['description','rule']);
return [
'message' => 'Success.',
'reports' => $reports,
];
From this array, I only want to return the fields 'description' and 'rule'. However I also want to return the owner() relationship from the Report model. How could I do this? Do I have to load the relationship and do some kind of array push, or is there a more elegant solution?
You can use with() to eager load related model
$reports = Report::with('owner')
->where('submission_id', $submissionID)
->where('status', 'pending')
->get(['id','description','rule']);
Note you need to include id in get() from report model to map (owner) related model
you will have probably one to many relationship with Reports and owners table like below
Report Model
public function owner() {
return $this->belongsTo('App\Owner');
}
Owner Model
public function reports() {
return $this->hasMany('App\Report');
}
your controller code
$reports = Report::with('owner')->
where('submission_id', $submissionID)->where('status', 'pending')->get()
return [
'message' => 'Success.',
'reports' => $reports,
];
This is what I ended up going with:
$reports = Report::
with(['owner' => function($q)
{
$q->select('username', 'id');
}])
->where('submission_id', $submissionID)
->where('status', 'pending')
->select('description', 'rule','created_by')
->get();
The other answers were right, I needed to load in the ID of the user. But I had to use a function for it to work.

Dynamic search function Photo album

I am trying to create a dynamic serch function to my PhotoAlbumn project. So I have installed Nicolaslopezj Searchable. However it does not work propertly as yet.
Error
Illuminate\Database\Eloquent\RelationNotFoundException
Call to undefined relationship [albums] on model [App\Photo]
Model
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;
class Photo extends Model{
use SearchableTrait;
protected $searchable = [
/**
* Columns and their priority in search results.
* Columns with higher values are more important.
* Columns with equal values have equal importance.
*
* #var array
*/
'columns' => [
'albums.name' => 10,
'photos.title' => 10,
'photos.info' => 10,
'albums.title' => 5,
],
'joins' => [
'albums' => ['photos.id','albums.id'],
],
];
protected $fillable = array('photo','title','info','album_id');
public function album(){
return $this->belongsTo('App\Album');
}
PhotoController
public function search(Request $request){
$query = $request->input('query');
$result = Photo::search($query)
->with('albums')
->get();
return view('search.results')->with('result', $result);
}
This relationship worked prior to using Nicolaslopezj Searchable.
You have an extra s in your relationship.
Replace
$result = Photo::search($query)
->with('albums')
->get();
by
$result = Photo::search($query)
->with('album')
->get();

How to change result of laravel relationship

I have an one to one relationship in laravel same as following:
public function Category()
{
return $this->belongsTo(Categories::class);
}
and run this eloquent query:
Product::with('category')->first();
this query return:
{
"name": "Green Book",
"category": {
"id": 1,
"name": "Book"
}
}
but I went this data:
{
"name": "Green Book",
"category": "Book"
}
Is it possible to do this without using a loop?
First of all it seems like you have a 1-X relationship which you are mistakenly using as a many to one. Your belongsTo should be hasOne since the your items have one category not the other way around.
You can use the $appends property to append a custom field and make it behave as though it's part of your model:
Rename your relationship and add a mutator and accessor:
public function categoryRelationship()
{
return $this->hasOne(Categories::class);
}
public function getCategoryAttribute() {
return $this->categoryRelationship->name;
}
public function setCategoryAttribute($value) {
$this->categoryRelationship->name = $value;
}
You can also choose to add an event to automatically save your relationship when the model is being saved to ensure it works transparently:
protected static function booted()
{
static::saving(function ($myModel) {
$myModel->categoryRelationship->save();
});
}
}
Finally you add the $appends property to ensure your new attribute is alwasy included in the model as though it's a native one.
protected $appends = [ 'category' ];
// This is so you don't end up also showing the relationship
protected $hidden = [ 'categoryRelationship' ];
You can use leftJoin
return \App\Product::leftJoin('categories', 'products.category_id', '=', 'categories.id')
->select('products.*', 'categories.title as category')->get();
According to Laravel Doc Eager Loading Specific Columns
You may use the following
Product::with('category:id,name')->first();
Or you may do it yourself :
$product = Product::with('category')->first();
$product->category = $product->category->name;
I get same result
so, i tried but didn't get right result.
how to change the result of laravel eloquent relation.
I found one way and used transformer.
we can change the result in transformer.
$result = Event::with(['eventType'])
->where('id', $id)
->where('user_id', auth()->user()->id)
->first();
return $this->trans->transform($result);
this is the result and i used transformer as follow.
public function transform(Event $Event)
{
return [
'id' => $Event->id,
'company_id' => $Event->company_id,
'calendar_id' => $Event->calendar_id,
'case_id' => $Event->case_id,
'user_id' => $Event->user_id,
'title' => $Event->title,
'description' => $Event->description,
'duration' => $Event->duration,
'alert_at' => $Event->alert_at,
'alert_email' => $Event->alert_email,
'email_sent' => $Event->email_sent,
'alert_popup' => $Event->alert_popup,
'popup_triggered' => $Event->popup_triggered,
'created_by' => $Event->created_by,
'completed' => $Event->completed,
'alert_offset' => $Event->alert_offset,
'icon' => $Event->icon,
'color' => $Event->color,
'snoozed' => $Event->snoozed,
'type_id' => $Event->type_id,
'datetime' => $Event->at,
'endtime' => $Event->end_time,
'event_type_name'=>$Event->eventType->name,
];
}
then, we can get right result. Focuse on 'event_type_name'=>$Event->eventType->name,
But i have one problem yet.
now, the result is only 1 row. it is just first().
but if i use get(), i can't use transformer.
of course, i can loop the result using foreach().
but i think it is not right way.
what is better way?
Please answer.

Can not format datetime in laravel 7.2.2

i am currently working in laravel 7.2.2 and I am trying to format following datetime in to 'M d Y' .
"created_at": "2020-03-23T12:17:29.000000Z",
Previously, in laravel 6, datetime formats are like this: 2019-12-02 20:01:00.
but now, date format is changed, and appearing like above: 2020-03-23T12:17:29.000000Z.
In laravel 6 i used to format my datetime as following code:
foreach ($posts as $post) {
$createdAt = Carbon::parse($post['created_at']);
$post['created_at'] = $createdAt->format('M d Y');
}
But it gives me same output as above 2020-03-23T12:17:29.000000Z .
So, how can i format my datetime in laravel 7.
Any help?
This was a breaking change introduced in Laravel 7.0. You can still format it the way you want.
You can override the serializeDate method on your model:
/**
* Prepare a date for array / JSON serialization.
*
* #param \DateTimeInterface $date
* #return string
*/
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('M d Y');
}
See the docs in the upgrade guide for more information.
HTH
You can use Eloquent resources to transform the data from your model to what the API should respond with. That way you won't need to touch the data and how the data is saved in your model.
It could look like something like this, given that your column names are the same:
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;
class Post extends JsonResource
{
public function toArray(Request $request)
{
return [
'id' => $this->id,
'title' => $this->title,
'text' => $this->text,
'created_at' => $this->created_at->format('M d Y'),
'updated_at' => $this->updated_at->format('M d Y'),
];
}
}

Pluck with multiple columns?

When i use pluck with multiple columns i get this:
{"Kreis 1 \/ Altstadt":"City","Kreis 2":"Enge","Kreis 3":"Sihifeld","Kreis 4":"Hard","Kreis 5 \/ Industriequartier":"Escher Wyss","Kreis 6":"Oberstrass","Kreis 7":"Witikon","Kreis 8 \/ Reisbach":"Weinegg","Kreis 9":"Altstetten","Kreis 10":"Wipkingen","Kreis 11":"Seebach","Kreis 12 \/ Schwamendingen":"Hirzenbach"
But i need this?
["Rathaus","Hochschulen","Lindenhof","City","Wollishofen","Leimbach","Enge","Alt-Wiedikon","Friesenberg","Sihifeld","Werd","Langstrasse","Hard","Gewerbechule","Escher Wyss","Unterstrass","Oberstrass","Fluntern","Hottingen","Hirslanden","Witikon","Seefeld","M\u00fchlebach","Weinegg","Albisrieden","Altstetten","H\u00f6ngg","Wipkingen","Affoltern","Oerlikon","Seebach","Saatlen","Schwamendingen-Mitte","Hirzenbach"]
Any suggestion how can i do that? This is my method:
public function autocomplete_districts(Request $request)
{
$district = $request->input('query');
// $ass = /DB::table('districts')->select(array('district', 'region'))->get();
// dd($ass);
$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->pluck('region','district');
return response()->json($data);
}
You should use select() with get() and then later on modify the object as you need.
So instead of: ->pluck('region','district');
use: ->select('region','district')->get();
pluck() is advised when you need value of one column only.
And as far as possible, you should have your models singular form not plural (Districts) - to follow Laravel nomenclature.
Cos that is how pluck works. Instead try this.
$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();
$data = collect($data->toArray())->flatten()->all();
In my case I wanted to pluck 2 values from an array of Eloquent models and this worked:
$models->map->only(['state', 'note'])->values()
That's shorter version of
$models->map(fn($model) => $model->only(['state', 'note']))->values()
This is an issue I constantly have faced and has led me to create the following solution that can be used on models or arrays.
There is also support for dot syntax that will create a multidimensional array as required.
Register this macro within the AppServiceProvider (or any provider of your choice):
use Illuminate\Support\Arr;
/**
* Similar to pluck, with the exception that it can 'pluck' more than one column.
* This method can be used on either Eloquent models or arrays.
* #param string|array $cols Set the columns to be selected.
* #return Collection A new collection consisting of only the specified columns.
*/
Collection::macro('pick', function ($cols = ['*']) {
$cols = is_array($cols) ? $cols : func_get_args();
$obj = clone $this;
// Just return the entire collection if the asterisk is found.
if (in_array('*', $cols)) {
return $this;
}
return $obj->transform(function ($value) use ($cols) {
$ret = [];
foreach ($cols as $col) {
// This will enable us to treat the column as a if it is a
// database query in order to rename our column.
$name = $col;
if (preg_match('/(.*) as (.*)/i', $col, $matches)) {
$col = $matches[1];
$name = $matches[2];
}
// If we use the asterisk then it will assign that as a key,
// but that is almost certainly **not** what the user
// intends to do.
$name = str_replace('.*.', '.', $name);
// We do it this way so that we can utilise the dot notation
// to set and get the data.
Arr::set($ret, $name, data_get($value, $col));
}
return $ret;
});
});
This can then be used in the following way:
$a = collect([
['first' => 1, 'second' => 2, 'third' => 3],
['first' => 1, 'second' => 2, 'third' => 3]
]);
$b = $a->pick('first', 'third'); // returns [['first' => 1, 'third' => 3], ['first' => 1, 'third' => 3]]
Or additionally, on any models you may have:
$users = User::all();
$new = $users->pick('name', 'username', 'email');
// Might return something like:
// [
// ['name' => 'John Doe', 'username' => 'john', 'email' => 'john#email.com'],
// ['name' => 'Jane Doe', 'username' => 'jane', 'email' => 'jane#email.com'],
// ['name' => 'Joe Bloggs', 'username' => 'joe', 'email' => 'joe#email.com'],
// ]
It is also possible to reference any relationship too using the dot notation, as well as using the as [other name] syntax:
$users = User::all();
$new = $users->pick('name as fullname', 'email', 'posts.comments');
// Might return something like:
// [
// ['fullname' => 'John Doe', 'email' => 'john#email.com', 'posts' => [...]],
// ['fullname' => 'Jane Doe', 'email' => 'jane#email.com', 'posts' => [...]],
// ['fullname' => 'Joe Bloggs', 'email' => 'joe#email.com', 'posts' => [...]],
// ]
My solution in LARAVEL 5.6:
Hi, I've just had the same problem, where I needed 2 columns combined in 1 select list.
My DB has 2 columns for Users: first_name and last_name.
I need a select box, with the users full name visible and the id as value.
This is how I fixed it, using the pluck() method:
In the User model I created a full name accessor function:
public function getNameAttribute() {
return ucwords($this->last_name . ' ' . $this->first_name);
}
After that, to fill the select list with the full name & corresponding database id as value, I used this code in my controller that returns the view (without showing users that are archived, but you can change the begin of the query if you like, most important are get() and pluck() functions:
$users = User::whereNull('archived_at')
->orderBy('last_name')
->get(['id','first_name','last_name'])
->pluck('name','id');
return view('your.view', compact('users'));
Now you can use the $users in your select list!
So first, you GET all the values from DB that you will need,
after that you can use any accessor attribute defined for use in your PLUCK method,
as long as all columns needed for the accessor are in the GET ;-)
As far as now Laravel didn't provide such macro to pick specific columns, but anyway Laravel is out of the box and lets us customize almost everything.
Tested in Laravel 8.x
in AppServiceProvider.php
use Illuminate\Support\Collection;
// Put this inside boot() function
Collection::macro('pick', function (... $columns) {
return $this->map(function ($item, $key) use ($columns) {
$data = [];
foreach ($columns as $column) {
$data[$column] = $item[$column] ?? null;
}
return $data;
});
});
Usage
$users = App\Models\User::all();
$users->pick('id','name');
// Returns: [['id' => 1, 'name' => 'user_one'],['id' => 2, 'name' => 'user_two']]
Important notes:
Do not use this macro for a really HUGE collection (You better do it on Eloquent
select or MySQL query select)
Laravel: To pluck multi-columns in the separate arrays use the following code.
$Ads=Ads::where('status',1);
$Ads=$Ads->where('created_at','>',Carbon::now()->subDays(30));
$activeAdsIds=$Ads->pluck('id'); // array of ads ids
$UserId=$Ads->pluck('user_id'); // array of users ids
I have created the model scope
More about scopes:
https://laravel.com/docs/5.8/eloquent#query-scopes
https://medium.com/#janaksan_/using-scope-with-laravel-7c80dd6a2c3d
Code:
/**
* Scope a query to Pluck The Multiple Columns
*
* This is Used to Pluck the multiple Columns in the table based
* on the existing query builder instance
*
* #author Manojkiran.A <manojkiran10031998#gmail.com>
* #version 0.0.2
* #param \Illuminate\Database\Eloquent\Builder $query
* #param string $keyColumn the columns Which is used to set the key of array
* #param array $extraFields the list of columns that need to plucked in the table
* #return \Illuminate\Support\Collection
* #throws Illuminate\Database\QueryException
**/
public function scopePluckMultiple( $query, string $keyColumn, array $extraFields):\Illuminate\Support\Collection
{
//pluck all the id based on the query builder instance class
$keyColumnPluck = $query->pluck( $keyColumn)->toArray();
//anonymous callback method to iterate over the each fileds of table
$callBcakMethod = function ($eachValue) use ($query)
{
$eachQuery[$eachValue] = $query->pluck( $eachValue)->toArray();
return $eachQuery;
};
//now we are collapsing the array single time to get the propered array
$extraFields = \Illuminate\Support\Arr::collapse( array_map($callBcakMethod, $extraFields));
// //iterating Through All Other Fields and Plucking it each Time
// foreach ((array)$extraFields as $eachField) {
// $extraFields[$eachField] = $query->pluck($eachField)->toArray();
// }
//now we are done with plucking the Required Columns
//we need to map all the values to each key
//get all the keys of extra fields and sets as array key or index
$arrayKeys = array_keys($extraFields);
//get all the extra fields array and mapping it to each key
$arrayValues = array_map(
function ($value) use ($arrayKeys) {
return array_combine($arrayKeys, $value);
},
call_user_func_array('array_map', array_merge(
array(function () {
return func_get_args();
}),
$extraFields
))
);
//now we are done with the array now Convert it to Collection
return collect( array_combine( $keyColumnPluck, $arrayValues));
}
So now the testing part
BASIC EXAMPLE
$basicPluck = Model::pluckMultiple('primaryKeyFiles',['fieldOne', 'FieldTwo']);
ADVANCED EXAMPLE
$advancedPlcuk = Model::whereBetween('column',[10,43])
->orWhere('columnName','LIKE', '%whildCard%')
->Where( 'columnName', 'NOT LIKE', '%whildCard%')
->pluckMultiple('primaryKeyFiles',['fieldOne', 'FieldTwo']);
But it returns the \Illuminate\Support\Collection, so if you need to convert to array
$toArrayColl = $advancedPluck->toArray();
if you need to convert to json
$toJsonColl = $advancedPluck->toJson();
To answer the specific question of "how to return multiple columns using (something like) pluck" we have to remember that Pluck is a Collection member function. So if we're sticking to the question being asked we should stick with a Collection based answer (you may find it more beneficial to develop a model-based solution, but that doesn't help solve the question as posed).
The Collection class offers the "map" member function which can solve the posed question:
$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])
->map(function ($item, $key, $columns=['region','district']) {
$itemArray = [];
foreach($columns as $column){
$itemArray[$column] = $item->$column;
}
return ($itemArray);
});
dd($data);
This should give you a collection where each element is a 2 element array indexed by 'region' and 'district'.
Laravel 8.x, try to use mapWithKeys method instead of pluck, for example:
$collection->mapWithKeys(function ($item, $key) {
return [$key => $item['firstkey'] . ' ' . $item['secondkey']];
});
Expanding on #Robby_Alvian_Jaya_Mulia from above who gave me the idea. I needed it to also work on a relationship. This is just for a single relationship, but it would probably be easy to nest it more.
This needs to be put into AppServiceProvider.php
use Illuminate\Support\Collection;
// Put this inside boot() function
Collection::macro('pick', function (... $columns) {
return $this->map(function ($item, $key) use ($columns) {
$data = [];
foreach ($columns as $column) {
$collection_pieces = explode('.', $column);
if (count($collection_pieces) == 2) {
$data[$collection_pieces[1]] = $item->{$collection_pieces[0]}->{$collection_pieces[1]} ?? null;
} else {
$data[$column] = $item[$column] ?? null;
}
}
return $data;
});
});
Usage:
$users = App\Models\User::has('role')->with('role')->all();
$users->pick('id','role.name');
// Returns: [['id' => 1, 'name' => 'role_name_one'],['id' => 2, 'name' => 'role_name_two']]
Hope this is helpful to someone. Sorry I didn't add this to under #Robby's answer. I didn't have enough reputation.
Pluck returned only the value of the two columns which wasnt ideal for me, what worked for me was this :
$collection->map->only(['key1', 'key2'])->values()

Resources