Laravel - what does the manual paginations 'option' query parameter do? - laravel

The manual pagination I found while googling works fine but I was just wondering what does the 'query' => $request->query() in the option parameter does?
$total = count($form_list);
$per_page = 10;
$current_page = $request->input('page') ?? 1;
$starting_point = ($current_page * $per_page) - $per_page;
$form_list = array_slice($form_list, $starting_point, $per_page, true);
$form_list = new Paginator($form_list, $total, $per_page, $current_page, [
'path' => $request->url(),
'query' => $request->query(),
]);

Calling ->query() without any parameters returns all the values from the query string as an associative array.
Suppose you have a query string like this:
https://example.com/path/to/page?name=ferret&color=purple
You can retrieve the value of name by doing something like so:
$request->query('name')
which returns ferret. You can also pass a second parameter for a default value so if you call:
$request->query('size', 'Medium')
which doesn't exist on the query string, you'll get 'Medium' instead of null.
If you omit all parameters, you'll receive an associative array that looks something like this:
query = [
'name' => 'ferret',
'color' => 'purple',
]
The options parameter is not needed by the pagination itself but for your dataset query. If you do not pass the query parameter, when you click one of the pagination urls, you'll get something like this:
https://example.com/path/to/page?page=2&per_page=5
Sometimes, this works fine and will give us something that we want but sometimes, we need those additional query string to get the correct dataset. We pass in all values from our query to get something like this:
https://example.com/path/to/page?page=2&per_page=5&name=ferret&color=purple
Which will filter your dataset for all those purple ferrets. As for the question if you need it, it's up for you to decide if that is essential for your code or if you can get away with just pagination.
Good luck! I hope this helps.

Related

how to use increment function in laravel

i am using DB to store values in database.
i have "course fees" column i what to "increment" the "course_fees" value in column.
for example
DB::table('student')->where('registration_id','=', $request->registration_id)->increment(['course_fees' =>$request->course_fees]);
this code increment the inserted value
how can i modified below code for increment "course_fees" value like above
DB::table('student')->where('registration_id','=', $request->registration_id)->update(['payment_date' => $request->payment_date,'balance_fees' => $request->balance_fees,'course_fees' =>$request->course_fees]);
You cannot use this method to increment multiple fields. You can use:
$studentQuery = DB::table('student')->where('registration_id','=', $request->registration_id);
(clone $studentQuery)->increment('payment_date',$request->payment_date);
(clone $studentQuery)->increment('balance_fees', $request->balance_fees);
(clone $studentQuery)->increment('course_fees', $request->course_fees);
but this way you will run 3 database queries to update.
But if you are sure there is exactly single record found for registration_id you can do it like this:
$student = DB::table('student')->where('registration_id','=', $request->registration_id)->first();
$student->update([
'payment_date' => $student->payment_date + $request->payment_date,
'balance_fees' => $student->balance_fees + $request->balance_fees,
'course_fees' => $student->course_fees + $request->course_fees
]);
EDIT
If you want to increment only course_fees column and want to update other 2 columns from input you can use:
DB::table('student')->where('registration_id','=', $request->registration_id)
->increment('course_fees' , $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees
])
This is documentation about increment/decrement methods.
increment()/decrement() can take 3 parameters: $column, $amount, $extra.
$column is the field that you want to increment
$amount is by how much you want to increment the field by
$extra is an array of attributes that you also want to update in the query.
If you don't pass an amount the default for $amount is 1.
To achieve what you're after you could do:
DB::table('student')
->where('registration_id', $request->registration_id)
->increment('course_fees', $request->course_fees, [
'payment_date' => $request->payment_date,
'balance_fees' => $request->balance_fees,
]);

How to append key value to the result of factory()->make() in Laravel?

I am writting a Test Case.
Lets say there is a Threads model with fields: user_id, title, body
So to test wheather submitting the Thread works, I am doing this:
$user = factory('App\User')->create();
$thread = factory('App\Thread')->make(['user_id' => $user->id]);
$this->post('/threads', $thread->toArray());
$this->get('/thread/'.$thread->id)
->assertSee($thread->title)
But I have yet another field that I want to post along with the thread which is not part of the thread model.
eg.
community => 'some_community'
So how do I append another field before posting the array to /threads.
How can I append key value pair to the result of make() ???
You can use the data_set function:
$thread = factory('App\Thread')->make(['user_id' => $user->id]);
$payload = $thread->toArray();
$this->post('/threads', data_set($payload, 'community', 'some_community'));

CodeIgniter 3.1.7 unbuffered_row() returning NULL but row() works

I am attempting to output a CSV from a query result. dbutil->csv_from_result() should work, but it only returns the column headers. No data is included.
I tracked it down to system/database/DB_utility.php which uses unbuffered_row().
Any calls to unbuffered_row() return NULL. If I change it to row(), I get a result. It makes no difference if I use unbuffered_row('array') or unbuffered_row('object')
Why does row() work but unbuffered_row() does not?
Is this a bug in CI or am I missing something?
Edit: row('array') doesn't seem to work either.
Edit: It seems that calling $query->result() spoils dbutil->csv_from_result($query). You apparently cannot iterate through query results AND then save the results in a CSV file. This was possible in CI 2.
Is there any way to show query results AND save the CSV without running the query twice?
I have faced similar problem and found this:
I have this query:
$query = $this->db->query("SELECT * FROM tablename");
print_r($query);
Then I get this and unbuffered_row works fine:
CI_DB_oci8_result Object
(
[stmt_id] => Resource id #106
[curs_id] =>
[limit_used] =>
[commit_mode] => 32
[conn_id] => Resource id #91
[result_id] => 1
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] =>
[row_data] =>
)
BUT if I call $query->num_rows() before I get a different CI_DB_oci8_result object and unbuffered_row didn't work returning null
$query = $this->db->query("SELECT * FROM tablename");
echo $query->num_rows();
print_r($query);
Hope this help somebody.

Delete from elasticsearch all items where field does not match a certan value

I'm trying to delete all items from Elasticsearch index where field time_crawl_started does NOT match a specific value. I'm using match_all query in combination with NOT filter.
This is what I got so far:
$client = new Elasticsearch\Client();
$params = Array(
'index' => ...,
'type' => ...
);
$params['body']['query']['filtered']['query']['match_all'] = Array();
$params['body']['query']['filtered']['filter']['not']['term']['time_crawl_started'] = $someDate;
$client->deleteByQuery($params);
The problem is that this deletes all items, even ones having time_crawl_started set to $someDate, which is simply a datetime such as "2014-02-17 19:13:31".
How should I change this to delete only the items that don't have the correct date?
The problem was that time_crawl_started field was analyzed and thus any comparison by value was wrong. I had to create index manually (as opposed to automagically by just inserting a new document into non-existing index) and specify mapping for my item type, setting 'index' => 'not_analyzed' for time_crawl_started.
And I ended up using script filter like this:
$params['body']['query']['filtered']['query']['match_all'] = Array();
$params['body']['query']['filtered']['filter']['script']['script'] = "doc['time_crawl_started'].value != \"" . $someDate . "\"";

Codeigniter Active Record return type

I tried to get a umat_id with this SQL query :
SELECT umat_id FROM msumat WHERE nama = $nama
I converted this SQL query into CI's Active Record :
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
So this query should return a string (example : "John").
But I got an error when I tried to echo it :
Object of class CI_DB_mysql_result could not be converted to string
I have tried something like this : echo (string)$terdaftar;, but it's not working.
All I want is to echo "John"
EDIT
Just said I want to insert "John" into a variable. How to do that?
$john = ????
As some of the users already pointed the solution, I'm only explaining why you did get this error so you can understand better the querying results that codeigniter gives.
This error:
But I got an error when I tried to echo it : Object of class
CI_DB_mysql_result could not be converted to string
Happens because you were trying to echo an object.
This piece of code
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
Will return an object, this object will have information about the query you've done.
With this object you can get the result(rows) as objects doing this:
$results = $terdaftar->result();
Or you if you feel more comfortable with arrays you can return the results(rows) as an array doing this:
$results = $terdaftar->result_array();
You can also get the number of results doing this:
$number_results = $terdaftar->num_rows()
And this is just an example you can read more about the results here
http://ellislab.com/codeigniter/user-guide/database/results.html
EDIT
A better explanation: imagine that we use the result_array() function to get the result in a pure array format:
$results = $terdaftar->result_array();
Now your variable $results is an array, to iterate through it and get the data you want you'll do something like this:
foreach ($results as $key => $row) {
//the row variable will have each row of your database returned by your query
//so if you want to access a field from that row,
//let's say for example the name field. You would do something like this
if($row['name']=='John')
echo $row['name'];
}
Try:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
foreach ($terdaftar->result() as $row)
{
echo $row->umat_id;
}
Read the documentation for more information.
Try this:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
$row = $terdaftar->row_array();
$your_variable = $row['umat_id']; /*Here comes your john*/

Resources