I'm trying to implement pagination and here is what I have so far.
In my main controller:
public function showIndex()
{
$countries = Country::paginate(5);
return View::make('index')->with('countries', $countries);
}
And in my view I'm simply doing:
<?php print_r($countries); ?>
However, that outputs an insanely long error, too long to post here in full:
Illuminate\Pagination\Paginator Object ( [factory:protected] =>
Illuminate\Pagination\Factory Object ( [request:protected] =>
Illuminate\Http\Request Object ( [json:protected] => [sessionStore:protected]
=> [attributes] => Symfony\Component\HttpFoundation\ParameterBag Object (
[parameters:protected] => Array ( ) ) [request] =>
Symfony\Component\HttpFoundation\ParameterBag Object ( [parameters:protected]
=> Array ( ) ) [query] => Symfony\Component\HttpFoundation\ParameterBag
Object ( [parameters:protected] => Array ( ) ) [server] =>
Symfony\Component\HttpFoundation\ServerBag Object ( [parameters:protected] =>
Array ([HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0)
Gecko/20100101 Firefox/36.0 [HTTP_ACCEPT] =>
text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,
deflate [HTTP_COOKIE] =>
What am I doing wrong? Am I missing something?
I'm going to post an answer here for the sake of clarification. The "error" you're getting isn't an error at all. It is, however, insanely long because it's printing recursively the entire collection returned from the ::paginate(5) method. If you scroll to the very bottom of this print_r statement, you should be able to make our your result set. For example, look for the id of one of your results and you should see something like Array ([id] => 1 [column_2] => x [column_3] => y ... where column_N are the names of the columns in your table.
Easiest rule of thumb when using Laravel:
If you return a collection, use a foreach loop.
And by that I mean if you use the methods ->get() or ->paginate(), go through your results using #foreach($items AS $item).
Hope that provided some clarification.
To answer my own question, all I had to do was add a loop in the view to loop through the database results:
#foreach ($countries as $country)
<div class="title">{{ $country->name }}</div>
#endforeach
{{ $countries->links() }}
Related
Hello everyone recently i started a project on Laravel 7.x but i have some problems.
I made a search with laravel default pagination.
This is my code:
Search form
<form action="/search" method="GET">
<input type="text" name="k" id="k" value="" placeholder="Search...">
<button type="submit">Search</button>
</form>
Controller
public function get_search(Request $request)
{
$keyword = request('k');
$data = DB::table('posts')
->where('title', 'LIKE', '%$keyword%')
->orderBy('id', 'DESC')
->paginate(20);
return view('search', ['data' => $data]);
Route
Route::get('/search',['uses' => 'MainController#get_search', 'as' => 'search']);
View
#foreach($data as $item)
{{ $item->title }}
#endforeach
{{ $data->links() }}
So i'm getting url like /search?key=keyword&page=2
All i want is to make looks like /search/keyword/page/2/
Thanks!
Replace ->paginate(20)
by ->paginate(20, ['*'], 'page', $page)
It's not documented.
I suggest that you modify the routes/web.php file. Use route arguments
Route::get('/search/{keyword}/page/{page}', 'SearchController#index')->name('.search');
And then, on the controller,
public function index($keyword, $page){ //Receive parameters
$data = DB::table('posts')
->where('title', 'LIKE', '%$keyword%')
->orderBy('id', 'DESC')
->paginate(20);
return view('search', ['data' => $data]);
...
}
Ok, i made what did u said above and when getting print_r($data) on search blade i am getting this
Array
(
[current_page] => 1
[data] => Array
(
[0] => stdClass Object
(
[title] => keyword 1
)
[1] => stdClass Object
(
[title] => keyword 2
)
[2] => stdClass Object
(
[title] => keyword 3
)
[3] => stdClass Object
(
[title] => keyword 4
)
[4] => stdClass Object
(
[title] => keyword 5
)
[5] => stdClass Object
(
[title] => keyword 6
)
[6] => stdClass Object
(
[title] => keyword 7
)
[7] => stdClass Object
(
[title] => keyword 8
)
[8] => stdClass Object
(
[title] => keyword 9
)
[9] => stdClass Object
(
[title] => keyword 10
)
)
[first_page_url] => hxxp://xxxx.xxx/search/keyword?page=1
[from] => 1
[last_page] => 5
[last_page_url] => hxxp://xxxx.xxx/search/keyword?page=5
[next_page_url] => hxxp://xxxx.xxx/search/keyword?page=2
[path] => hxxp://xxxx.xxx/search/keyword
[per_page] => 10
[prev_page_url] =>
[to] => 10
[total] => 49
)
Shows the same results while i am replacing the url hxxp://xxxx.xxx/search/keyword/page/2/
Any URL outputs the same result, it's just changed the ?page=x, but the results are the same. basically the hxxp://xxxx.xxx/search/keyword/page/2/ does nothing.
The results are changing only if i change the url to hxxp://xxxx.xxx/search/keyword/page/2/?page=2 which i don't need to..
In laravel 5.8 making request
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->toArray();
I got resulting rows like :
$searchResultsArray::Array
(
[0] => Array
(
[field] => Id
[value] => 302530
)
[1] => Array
(
[field] => Domain
[value] => site.com
)
If there is a way to get
array of fieldname=>fieldvalue keys, like
Id => 302530
Domain=> site.com
without additive foreach block in my code?
If yes how?
Yes there is. Eloquent always returns collections. You could modify the collection first with mapWithKeys() (https://laravel.com/docs/5.8/collections#method-mapwithkeys) and then convert it to an array.
Try something like this:
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->mapWithKeys(function ($item) {
return [$item['field'] => $item['value']];
})
->all();
I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.
I was trying to save a form data to DB. In the controller save() function there is a statement
$data = $model->validate($form, $data);
But it always returns empty. I tracked down the problem to the filter() function in /libraries/joomla/form/form.php (comes with joomla package). Here is some code (shortened):
$input = new JRegistry($data);
$output = new JRegistry;
foreach ($fields as $field)
{
// Initialise variables.
$name = (string) $field['name'];
if ($input->exists($name)){
$output->set($name, $this->filterField($field, $input->get($name, (string) field['default'])));
}
}
$input looks like :
JRegistry Object ( [data:protected] => stdClass Object ( [jform] => stdClass Object ( [title] => Utility Model/Patent application [ap_name] => d ...) [option] => com_eipoapplications [task] => save ) )
And each $name in the loop always contain the form element name (like 'title', 'ap_name' ... ).
But the if conditional statement always returns false. Does any one help me know why JRegistry exists() function is not finding the elements?
I think you are having an inconsistency between form and data.
Let's say the form contains a field with name title.
$data array should have a value under key of same name:
$data = array(
'title' => 'Utility Model/Patent application',
'ap_name' => 'd'
);
Or using print_r
Array
(
[title] => Utility Model/Patent application
[ap_name] => d
)
If there's no data for such field, validation is omitted. If all data keys are wrong, function returns empty array.
The question is, how it happened :/
I set session in a controller function like
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
where $data['result'] is an array;
but if I try to access this variable in other function of same controller it shows nothing:
print_r($this->session->userdata('projectInfo'));
though on using print_r($this->session->userdata('search_count')); it shows correct value.
also if I use print_r($this->session->all_userdata()); in second function of same controller it does not show array value index which I have already set in first function
Array
(
[session_id] => 4adf3a42ee64ffca2b2f273cb293a10a
[ip_address] => 127.0.0.1
[user_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1
[last_activity] => 1347689522
[user_data] =>
)
If I'm correct you can't save arrays into a session without serializing them first.
$search = array(
'search_count' => count($data['result']),
'projectInfo' => $data['result']
);
$this->session->set_userdata($search);
Becomes:
$search = array(
'search_count' => count($data['result']),
'projectInfo' => serialize($data['result'])
);
$this->session->set_userdata($search);
Now if you want to retrieve the array:
$data = unserialize($this->session->userdata('projectInfo'));
print_r($data);
Please note that you should use the database to store sessions when you are setting large amounts of data in a session.
config.php
$config['sess_use_database'] = TRUE;
Thanks I added Native PHP Session Class