Fetching all database entries with their relationships using a Resource - laravel

So, I'm currently trying to fetch every entry from one database table and returning them using an APIResource. I wanna also return every relationship of those entries.
Here is my controller:
public function all()
{
return GameResource::collection(Game::all()->with('white_user', 'black_user', 'win_user')->get());
}
And the corresponding Resource:
public function toArray($request)
{
return [
'GmID' => $this->GmID,
'White_user' => new UserPublicResource($this->whenLoaded('white_user')),
'Black_user' => new UserPublicResource($this->whenLoaded('black_user')),
'Winner' => new UserPublicResource($this->whenLoaded('win_user')),
'Pgn' => $this->Pgn,
'StartTime' => $this->StartTime
];
}
I am aware that the Problem lies in the all() method which returns a collection which doesnt have a with() method.
Here is the error message:
Method Illuminate\Database\Eloquent\Collection::with does not exist.
I am wondering if there is an easy way to do what I want to and I can't seem to find anything in the docs or anyone on the internet who wanted something similar.

you are calling with after fetching data which is collection and collection don't have with method call this way will work it will fetch all data from game table.
return GameResource::collection(Game::with('white_user', 'black_user', 'win_user')->get());

Related

delete() not working on Eloquent in laravel

delete() not working on Eloquent in laravel and getting the call to member function error. Like is just a simple model.
$matchThese = ['snippet_id' => $snippet_id, 'user_id' => $user_id];
$likedsnippet = Like::where($matchThese)->get();
$likedsnippet->delete();
Is Like has a child, or attached relationship? If yes, you first need to detach the connection or delete the child object as well.
If Like is a simple object, is it exists at all?
Maybe the object with the conditions you are searching for does not exists. Try to dd the like object before the delete, or wrap it around with:
if(isset($likedsnippet))
{
$likedsnippet->delete();
}
Or you can try to delete the objects one by one using a foreach:
foreach($likedsnippet as $obj)
{
$obj->delete();
}
Eloquent's get method return an Collection instance and collections don't have delete method. You can rewrite the query like this:
Like::where($matchThese)->delete();
it looks like there are only one deleting model in your application, if it's So, you can use first method.
$likedsnippet = Like::where($matchThese)->first();
$likedsnippet->delete();

Call to a member function first() on null

When I try to fetch my user data, I receive the error
Call to a member function first() on null
public function show($id) {
$user=User::findOrFail($id);
$employee = $user->employees->first();
return view('admin.profile')
->with(['employee' => $employee , 'user' => $user]);
}
The problem is probably in your User model.
Check that you have declared the employees relationship:
public function employees()
{
return $this->hasMany(Employee::class); // I'm assuming you have a Employee model with expected column names, but feel free to replace everything with what you actually have in your app
}
If the problem persists, edit your question with your tables structure and your models.
It's very useful to understand the difference between $user->employees and $user->employees().
$user->employees: returns a Collection of employee models, or null if none are found.
$user->employees(): returns a query builder instance that you can chain additional conditions to (where's, etc).
Both options have a first() option available to them, but one is using a Collection method, where the other is using the query builder method.
Some have already suggested this, and I will as well - the safer and simplest solution to your problem is to use the query builder version of the relationship, since there is no risk of the employees() result being null. It also has the added benefit of not needing to load the entire relationship into a collection just to get the first result.
In short: $user->employees()->first(); is the best way to go.

Using groupBy in Laravel resource

I want to pass a collection with a groupBy in laravel resource, But the problem is when i use that with collection method I can not modify the json and it throws a error:
PostResource:
public function toArray($request)
{
return [
'comments' => CommentResource::collection($this->comments->groupBy('star')),
];
}
Property [star] does not exist on this collection
But as soon as I remove the groupBy method from the collection it works. So how to get and modify the resource when it is grouped by with a specific key ?
"You could possibly group the collection once it has been created."
CommentResource::collection($this->comments)->collection->groupBy('star')
credits goes to devcircus with his answer on github
i use it and work successfully
CommentResource::collection($this->comments)->collection->groupBy('star')

Cannot merge on an Eloquent collection in Laravel

I need to merge either a collection or an array (it can be either) in Laravel 5.1, but I am getting the error BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::merge()
When I make a collection from scratch, I can merge to it, but I cannot merge onto the result of an Eloquent query, which I thought were collections as well. But perhaps that is not true?
Code that gives the error:
$user=User::where('user_last_name', 'Doe')->first();
$tomerge = collect(['book' => 'desk', 'foot' => 'chair']);
$newcollect = $user->merge($tomerge);
If I instead did $tomerge->merge($user) it works, but that's not what I actually need. Is there a way to use merge as I want?
To answer your question as to why it's not working...
$user = User::where('user_last_name', 'Doe')->first();
This is a single instance of a model. Not a collection. An eloquent model does not have the merge method.
If you want to append attributes to an Eloquent model, the simplest way is probably to use the $appends property and the appropriate accessor. For example, in your User model..
protected $appends = ['book', 'foot'];
public function getBookAttribute()
{
return 'desk';
}
public function getFootAttribute()
{
return 'chair';
}
However, note that this will affect every instance of your User model.

Converting Laravel-4 Eloquent query results to arrays

I'm trying to get my route to insert a new row into the database, and if successful return the record (with its new primary key id) in some JSON. I'm getting the following error:
{
"error":
{
"type":"BadMethodCallException",
"message":"Call to undefined method Illuminate\\Database\\Query\\Builder::to_array()",
"file":"\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php",
"line":1418
}
}
This is my route:
Route::post('/client/create', function()
{
$client = Client::create(Input::all());
if($client)
{
return json_encode(array('Result' => 'OK', 'Record' => $client->to_array()));
}
else
{
return json_encode(array('Result' => 'ERROR', 'Message' => 'Error Inserting Record =('));
}
});
According to the Laravel docs I've read, you're supposed to use ->to_array() to convert your model to an array, and ::create returns an instance of the model if successfully inserted. I've checked the database, and the records are being inserted just fine.
By default if you were to return an Eloquent model directly it would convert the model to it's JSON representation. This is because the __toString magic method on each model returns the model as JSON by using the toJson method.
As such the model implements both the ArrayableInterface and JsonableInterface. That means you can directly call toJson or toArray on a model.
Now you can mark columns as hidden. This means that when a model is converted into it's array or JSON representation some columns are removed (think publicly accessible API, you don't want passwords showing up!). I'm not totally sure but maybe the ID of your model is being hidden.
At the end of the day, all you need to do is return the instance.
return $client;
It'll be converted to JSON for you automatically.
The to_array() method comes from Laravel 3. Use toArray() in Laravel 4.
I see question similar you try to return data to jquery jtable and same me
Player::orderBy($sort)->paginate($pagesize)->getCollection();
return Response::view(array('Result'=>'OK','Records'=>$player->toArray()));
for try many hour I found solution getcollection pull instance from object and then solve

Resources