Getting the next object in a collection in Laravel - laravel

I have mutliple Chapters that belong to a Module.
On a chapter page I want to check if I am on the last one in the module, but I'm getting a bit stuck.
// inside Chapter model.
// The $module var is a made by something like Module::with('chapters')->find(1);
public function getNext($module){
// Convert to array so we can call some of
// the array functions to navigate the array
$chapters = $module->chapters->keyBy('id')->toArray();
// get the last element in the array
end($chapters);
// If the last element's key is the same as this one,
// there is no "next" link
if(key($chapters) == $this->id){
return false;
}
// So there must be a next link. First, reset internal array pointer
reset($chapters);
// Advance it to the current item
while (key($chapters) !== $this->id) next($chapters);
// Go one further, returning the next item in the array
next($chapters);
// current() is now the next chapter
return current($chapters);
}
Cool! So this lets me know if there is a next chapter and even returns it as an array with all of its data. But I'm getting into massive problems. The Chapter has a few other methods on it which I can't call on the 'next' element as its an array, not an object any more.
// Chapter.php
public function url(){
return url('chapter/' . $this->id);
}
$module = Module::with('chapters')->find(1);
$chapter = Chapter::find(1);
$next = $chapter->getNext($module);
if( $next )
echo $next->url();
This gives me (obviously)
Call to a member function url() on array
So I need to rewrite this function, but I can't work out how to get the next object in a Laravel collection.
public function getNext($module){
$last = $module->chapters->last();
// If the last element's key is the same as this one,
// there is no "next" link
if($last->id == $this->id){
return false;
}
....
How can I traverse the collection to get the next Chapter as an object?

After a little bit I have worked out my own solution:
public function getNext($module){
$last = $module->chapters->last();
// If the last element's key is the same as this one,
// there is no "next" link
if($last->id == $this->id){
return false;
}
$current_order = $this->order;
$filtered = $module->chapters->filter(function ($item) use ($current_order) {
return $item->order > $current_order;
});
return $filtered->first();
}
Open to any other neater ways of doing it though! Thanks

You can create collection macros as:
Collection::macro('previous', function ($key, $value = null) {
if (func_num_args() == 1) $value = $key; $key = 'id';
return $this->get($this->searchAfterValues($key, $value) - 1);
});
Collection::macro('next', function ($key, $value = null) {
if (func_num_args() == 1) $value = $key; $key = 'id';
return $this->get($this->searchAfterValues($key, $value) + 1);
});
Collection::macro('searchAfterValues', function ($key, $value) {
return $this->values()->search(function ($item, $k) use ($key, $value) {
return data_get($item, $key) == $value;
});
});
Then you can use it as:
$module = Module::with('chapters')->find(1);
$chapter = Chapter::find(1);
$next = $module->chapters->next($chapter->id)
// or
$next = $module->chapters->next('id', $chapter->id)

Related

How to remove One Item from session array in Laravel 8

i have create a session array like this:
public function addToCart($id, $qty){
$cart = session('Hami__cart');
$cart[$id] = ['quantity'=>$qty, 'color'=>'default', 'size'=>'default', 'id'=>$id];
session()->put('Hami__cart',$cart);
}
i have add 2 entries in this session it's look like this.
Now I want to remove one item from this array i am trying this code but it doesn't work :
public function RemoveCartItem($id){
$items = session('Hami__cart');
if($items != ""){
foreach ($items as $key => $values){
if($key == $id ){
session()->forget($items[$key]);
}
}
}
}
How to remove one item from this Session Array, i have also try unset() but it doesn't work.
public function RemoveCartItem($id){
$items = session('Hami__cart');
if($items != ""){
foreach ($items as $key => $values){
if($key == $id ){
unset($items[$key]);
}
}
session()->put('Hami__cart', $items);
}
}

pass an index to the method reduce() laravel

I have this function created to show a piechart but I need each element to show a different color. For this I have created an array with all the colors and I need in each iteration of the reduce() method to have an index to access the colors[i]. I have tried this way and it does not work. Any suggestion?
$i = 0;
$pieChartModel = $options->groupBy('survey_options_id')
->reduce(function (PieChartModel $pieChartModel, $data) use ($i) {
$type = $data->first()->survey_options_id;
$value = $data->sum('value');
// $color = "#" . substr(md5(rand()), 0, 6);
$NameOption = Survey_options::where('id', $type)->pluck('name');
return $pieChartModel->addSlice($NameOption, $value, $this->colors[$i]->hexa);
$i++;
}, (new PieChartModel())->setAnimated($this->firstRun)->setDataLabelsEnabled(true));
A problem I'm seeing in your code is how you're incrementing $i AFTER a return statement.
After taking a look at the source code for the reduce() function
/**
* Reduce the collection to a single value.
*
* #param callable $callback
* #param mixed $initial
* #return mixed
*/
public function reduce(callable $callback, $initial = null)
{
$result = $initial;
foreach ($this as $key => $value) {
$result = $callback($result, $value, $key);
}
return $result;
}
You should be able to use the key (or index) in the callback.
->reduce(function ($carry, $item, $key) { ... }, $initial)
->reduce(function (PieChartModel $pieChartModel, $data, $i) {
...
}, (new PieChartModel())->setAnimated($this->firstRun)->setDataLabelsEnabled(true))

Order items logic with Laravel

For my Laravel-application I've implemented a sort-functionality. In the list of the options I show two buttons (up and down) which trigger the functions up and down in the OptionController (see below).
Question 1
At the moment I am justing a DECIMAL(30,15) field for the sort-column in the database. I choose this 30,15 randomly. Can you give me an advice, which DECIMAL(?,?) is best for this sort field?
Question 2
I want to move the up and down logic to a place, where I can use it in different controllers with generic models (e.g. Sort::up($models, $item). What would be the right place to place such a logic? Service? Helper-function? ...?
Question 3
When I create a new item (e.g. option in my example below) I need to set the sort automatically to the sort of the last item + 1. Of course, I could do this in the controller when storing it, but can I put this logic to the model itself? And: Where can I put this logic to use it in more than one model without repeating the code?
namespace App\Http\Controllers;
use App\Models\Option;
use App\Models\Attribute;
class OptionController extends Controller
{
public function up($id, $attributeId) {
$options = Attribute::findOrFail($attributeId)->options;
$option = Option::findOrFail($id);
foreach ($options as $index => $o) {
// Search for the current position of the
// option we have to move.
if( $option->id == $o->id ) {
// Will be first element?
if( $index == 1) {
// Set the sort to current first element sort - 1
$option->sort = $options[0]->sort-1;
} else if( $index > 1) {
// Get the previous and the pre-previous items from the options
$pre = $options[$index-1]->sort;
$prepre = $options[$index-2]->sort;
$diff = ($pre - $prepre) / 2;
$option->sort = $prepre + $diff;
}
break;
}
}
$option->save();
Session::flash('message', __(':option moved up.', [ 'option' => $option->name ]));
Session::flash('message-type', 'success');
return redirect()->back();
}
public function down($id, $attributeId) {
$options = Attribute::findOrFail($attributeId)->options;
$option = Option::findOrFail($id);
foreach ($options as $index => $o) {
// Search for the current position of the
// option we have to move.
if( $option->id == $o->id ) {
// Will be last element?
if( $index == count($options)-2 ) {
// Set the sort to current last element sort + 1
$option->sort = $options[count($options)-1]->sort+1;
} else if( $index < count($options)-2) { // ???
// Get the previous and the pre-previous items from the options
$next = $options[$index+1]->sort;
$nextnext = $options[$index+2]->sort;
$diff = ($nextnext - $next) / 2;
$option->sort = $next + $diff;
}
break;
}
}
$option->save();
Session::flash('message', __(':option moved down.', [ 'option' => $option->name ]));
Session::flash('message-type', 'success');
return redirect()->back();
}
}
You can use a trait for this. See link for more details.

Laravel change pagination data

My Laravel pagination output is like laravel pagination used to be, but I need to change the data array for each object.
My output is:
As you can see, the data object has 2 items, which I need to change.
My code is:
$items = $this->items()
->where('position', '=', null)
->paginate(15);
Which returns the user items with pivot table, but I don't like the way the pivot table is shown in the JSON, so I decided to change the items and organize each item with the pivot before the item.
For this purpose, I tried to use foreach
foreach ($items->data as $item)
{
}
which giving my an error, for a reason I don't know:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$data"
status_code: 500
Any help?
The paginator's items is a collection. You can grab it and transform the data like so:
$paginator = $this->items()->where('position', '=', null)->paginate(15);
$paginator->getCollection()->transform(function ($value) {
// Your code here
return $value;
});
If you are familiar with tap helper here is the snippet that does exact same.
$paginator = tap($this->items()->where('position', '=', null)->paginate(15),function($paginatedInstance){
return $paginatedInstance->getCollection()->transform(function ($value) {
return $value;
});
});
We can't chain method getCollection to paginator instance because AbstractPaginator will return paginator's underlying collection. so the paginator instance will be transformed to Collection. So fix that we can use tap helper.
If you'd like to keep items paginated:
$itemsPaginated = $this->items()
->paginate(15);
$itemsTransformed = $itemsPaginated
->getCollection()
->map(function($item) {
return [
'id' => $item->id,
];
})->toArray();
$itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
$itemsTransformed,
$itemsPaginated->total(),
$itemsPaginated->perPage(),
$itemsPaginated->currentPage(), [
'path' => \Request::url(),
'query' => [
'page' => $itemsPaginated->currentPage()
]
]
);
There is a setCollection method for such purpose.
$items = Model::paginate(10);
$updatedItems = $items->getCollection();
// data manipulation
// ...
$items->setCollection($updateItems);
From the source code of /Illuminate/Pagination/AbstractPaginator.php
/**
* Set the paginator's underlying collection.
*
* #param \Illuminate\Support\Collection $collection
* #return $this
*/
public function setCollection(Collection $collection)
{
$this->items = $collection;
return $this;
}
Source
I could make shorter way. This returns edited $array instead of simple $paginated. This example modify file names.
This doc was useful for me.
$paginated=$query->paginate(12);
$array=$paginated->toArray();
foreach ($array['data'] as $r=>$record) {
$array['data'][$r]->gif=$array['data'][$r]->gif.".gif";
}
return $array;
Sample Example :
$franchiseData=[ 'id'=>1 ,'name'=>'PAnkaj'];
$models = $bookingsQuery->paginate(10);
$models->setCollection(collect($franchiseData));
return $models;
Note that $models->setCollection(collect($franchiseData)); you have to use collect() else you will get error.
getCollection
is one way to get the items. Another way is to use this
For ex- Assuming, user doesn't have name param and only have first_name and last_name
$userPaginatedData = User::paginate(15);
$users = $userPaginatedData->items();
foreach($users as $user) {
$user->name = $user->first_name . ' ' . $user->last_name;
}
return $userPaginatedData;
Now in the data key, you would see that each user has name param with it.
Laravel 8.9.0 has added the through method to AbstractPaginator.
It transforms each item in the slice of items using a callback, and keeps the items paginated.
$paginator = $this->items()->where('position', '=', null)->paginate(15);
$paginator->through(function ($value) {
// Your code here
return $value;
});
The source code:
/**
* Transform each item in the slice of items using a callback.
*
* #param callable $callback
* #return $this
*/
public function through(callable $callback)
{
$this->items->transform($callback);
return $this;
}
-Laravel 5.4
// example update column "photo"
// from "/path/to/photo.png"
// to "abc.com/path/to/photo.png"
foreach ($items as $item)
{
$path = $item->photo;
// Remove
$item->offsetUnset("photo");
// Set
$item->offsetSet("photo", url($path));
}
Laravel AbstractPaginator has methods setCollection() and getCollection()
<?php
$itemsPaginated = $this->items()->paginate(15);
$itemsPaginated->setCollection(
$itemsPaginated->getCollection()->transform(function ($item) {
// Your code here
return $item;
})
)
This is your paginated items...
$items = $this->items()
->where('position', '=', null)
->paginate(15);
I am using Laravel 8, can simply use each
$items->each(function ($item) {
// your code here
$item->custom_data = calcSomeData(); // sample
});
It does the same as this...
$items->getCollection()->transform(function ($item) {
// your code here
$item->custom_data = calcSomeData(); // sample
});
<?php
$itemsPaginated = $this->items()->paginate(15);
$itemsPaginated = json_encode($itemsPaginated);
foreach ($itemsPaginated->data as $key => $item) {
$results->data[$key]; //Modify
}
$itemsPaginated = json_encode($results);
you have to use below code in your blade
{!! $items->render() !!}
Ignore the pagination in laravel and hit the normal data
foreach ($items as $item)
{
}

Call to a member function row() on a non-object

i am getting error Call to a member function row() on a non-object in codeigniter my controller is
public function edit_survey_pro($id)
{
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (sizeof($survey) == 0) $this->template->error(lang("error_32"));
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
}
my model is
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
{
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
$this->db->limit($perpage,$start);
if($where){
$this->db->where($where);
}
if($order_by){
$this->db->order_by($order_by);
}
if($arr=='')
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
if(!empty($query))
if($perpage != 0 && $perpage != NULL)
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
here loadContent() is just load the content with view path
public function loadContent($view,$data=array(),$die=0){
//something to load the content
}
in my model I am getting the result as an array of object in $query and then it is returned as $result like this -
$query = $this->db->get()->result(); but at the controller $survey stores array of object and i want to show the content of that array of object ,previously I use
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
to get that data but the problem is $survey->row() cannot return that data bcoz it is not an object it is array of object so it can't be returned through row() method
so instead of this I just call the first element of that data like this-
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey[0]
)
);
Somehow its works for me bcoz I want to show the first row of the data
if sembody wants to show all data then I think he shuld try logic to increment the key value of that array of object for me it is $survey[] you can use foreach loop for increment the of value of the key element
The problems i see are your model, I will dissect it and add comments to your original code to point out the issues:
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
//above there are problems, you are setting some of your parameters to
//equal blank, but below, in your conditionals, you are checking if they
// exist. They will always exist if they are set to blank. Fix them by
// setting them = NULL like this:
// get($table,$where=null,$perpage=0,$start=0,$order_by=null,$arr=null)
{
$this->db->select();// <-- you forgot this
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
//when will $perpage = null? , if never, then you dont need it.
$this->db->limit($perpage,$start);
if($where){
//change this to if(isset($where)). Also why do you use
//curly braces here, but not in the above if statement if only
//one line is affected in your if. I would remove the
//curly braces here.
$this->db->where($where);
}
if($order_by){
// change this to if(isset($order_by)). Same thing as
//above about the curly braces here
$this->db->order_by($order_by);
}
if($arr=='')
// change this to if(isset($arr)).
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
//change this to: $query = $this->db->get()->result_array();
if(!empty($query))
//change the above to if($query->num_rows > 0). Also, here since
//your code body is longer then one line, you will need curly braces
//around your if statement
if($perpage != 0 && $perpage != NULL)
//again, will $perpage ever be NULL? However, why do you need
//this conditional at all, if the limit above is already
//doing this job?
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
after applying all the changes:
MODEL:
function get($table, $where=null, $perpage=0, $start=0, $order_by=null, $arr=null)
{
$this->db->select();
$this->db->from($table);
if($perpage != 0)
$this->db->limit($perpage, $start);
if(isset($where))
$this->db->where($where);
if(isset($order_by))
$this->db->order_by($order_by);
if(isset($arr)) {
$result = $this->db->get()->result_array();
} else {
$result = $this->db->get()->result();
}
return $result;
}
CONTROLLER
public function edit_survey_pro($id) {
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (!$survey) {
$this->template->error(lang("error_32"));
} else {
$data["survey"] = $survey;
$this->template->loadContent("user/edit_survey_pro", $data);
}
}
I think when you use $this->db->get(), you need to pass the table name as param like this:
$this->db->get('table_name')->result();

Resources