Using groupBy in Laravel resource - laravel

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')

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();

Fetching all database entries with their relationships using a Resource

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());

Update Table Using Laravel Model

I've got a table for a sports team. The record shows the team selection and some other information. I want to update the record with the team selection. My model is thus:
class Selection extends Model {
protected $table = "selection";
protected $fillable = [
'loose',
'hooker',
'tight',
'secrow1',
'secrow2',
'blindflank',
'openflank',
'eight',
'scrum',
'fly',
'leftwing',
'rightwing',
'fullback',
'sub1',
'sub2',
'sub3',
'sub4',
'sub5'
];
}
So I have a form which gives all the data for the positions and gives the id for the record in the DB. In my controller, I've got:
public function storeFirstTeam()
{
$input = Request::all();
Selection::update($input->id,$input);
return redirect('first-team');
}
But I get the following error:
Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically, assuming $this from incompatible context
Can anyone point out my silly error?
Please check the code below and this would solve your problem:
Selection::whereId($id)->update($request->all());
The error message tells you everything you know: you’re trying to call a method statically (using the double colons) that isn’t meant to be.
The update() method is meant to be called on a model instance, so first you need to retrieve one:
$selection = Selection::find($id);
You can then can the update() method on that:
$selection->update($request->all());
You should write it like given example below:
Selection::where('id', $input['id'])->update($input);
// Or use this using dynamic where
Selection::whereId($input['id'])->update($input);
Alternatively, you may write it like this as well:
Selection::find($input['id'])->fill($input)->save();
You can also simply update the fields manually:
Selection::whereId($id)->update($request->all());
it is possible to update with primary key but in my case I dont have id field in the detail table. To do it just run a query like this:
DB::table("shop_menu_detail")
->where(['name' => 'old name', 'language' => 'english'])
->update(['name' => 'new name']);
where is used as it is.

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