WhereBetween function in not working properly Laravel 5.0 - laravel-5

$dt = \Carbon::now();
$tomorrow = Carbon::tomorrow();
$yesterday = Carbon::yesterday();
$data = $this->model->select('id', 'description')
->whereBetween($dt, array($yesterday, $tomorrow))->get();
It is returning an error saying "An error occurred in database operation."

In the wherebetween clause the first argument should be table column field, which you are trying to compare.
For example:
$data = $this->model->select('id', 'description')
->whereBetween('created_date', array($yesterday, $tomorrow))->get();

Related

Laravel fetch raw query result

I don't want laravel to format my query result to an array or object ..etc. All I want, is to run the result set from database and then I will manually do the fetch myself in my custom code.
At the moment, I ran my select query and get my result in an array. The reasons for that, because the result is huge and I want to stream it directly to API.
$result = self::$db->select('select * from customer');
How can I tell laravel, to return my query result set without any format at all?
You can use DB:Raw like:
$results = DB::table('users')->select(DB::raw("*"))->get()
Or
$results = DB::select('select * from users where id = ?', [1]);
These two will return a neat object without any casts or relations etc. You can also make any object or array your API need by simple eloquent models by the way. Please explain more about data type you wanna extract from model query.
You must be use ->toSql() or ->dd()
Exapmle
Customer::toSql(); // select * from `customer`
if you want some condition
$query = Customer::where(`some conditions`);
$sql = $query->toSql();
$bindings = $query->getBindings();
$sql = str_replace('?', '%s', $sql);
$sql = sprintf($sql, ...$bindings);
Thanks everyone, I end up writing a raw function to query the data I want from database.
public static function dataStreamJSON($stmt, $headers)
{
return Response::stream(function() use ($stmt){
$conn = self::getConnection();
$result = sqlsrv_query($conn, "exec $stmt");
echo '
{
"Customers": {
"Customer": [';
$counter = 0;
while($customer = sqlsrv_fetch_object($result)) {
if($counter !== 0){
echo ",";
}
$counter++;
$row = [
'Firstname' => $customer->Firstname,
'Lastname' => $customer->Lastname,
...
];
echo json_encode($row);
unset($row);
unset($customer);
}
echo ']
}
}';
#sqlsrv_free_stmt($result);
#sqlsrv_close($conn);
}, 200, $headers);
}
The purpose of this code is to stream the data out to JSON format on browser without store the data in any variable, which will caused “out of memory” error.
I managed to stream 700MB of JSON data to the browser without any error. With this code, you will never run into “out of memory” error.
Best way to test this, is to use CURL to access your API and download the data to a JSON file. If you open on browser, it will freeze your screen because browser can't handle large data.
You can use toArray() or toJson() methods like below:
$array = Customer::all()->toArray();
$json = Customer::all()->toJson();
echo '<pre>';
print_r($array);
print_r($json);
If you want to run raw SQL Queries, you can do as below
$users = DB::select('select * from users where 1');
echo '<pre>';
print_r($users);
You can use
1) query builder way:-
DB::table('your_table_name)->select('your_col_names')->get();
eg:- DB::table('shop')->select('product_id','product_name')->get();
2) use laravel Raw
$orders = DB::table('orders')->selectRaw('price * ? as price_with_tax', [1.0825])->get();
3) for select raw
$product_count = DB::table('product')->select(DB::raw('count(*) as total_product_count'))->where('status',1)->get();

Laravel simplePaginate() for Grouped Data

I have the following query.
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);
When I try to paginate with the simplePaginate() method I get this error.
stripos() expects parameter 1 to be string, object given
How can I paginate grouped data in this case?
The created_at attribute is already casted as a Carbon Object (by default in laravel models). that's why you are getting that error. Try this:
$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
return $project->created_at->format('Y-m-d');
})->simplePaginate(5);
this answer is just for the error you're getting. now if you want help with the QueryBuilder, can you provide an example of the results you're expecting to have and an example of the database structure ?
The pagination methods should be called on queries instead of collection.
You could try:
$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');
The problem was solved. I was create custom paginator via this example:
https://stackoverflow.com/a/30014621/6405083
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 15; // Number of results per page
$count = Project::count(); // Get the total number of entries you'll be paging through
// Get the actual items
$projects = Project::orderBy('created_at', 'desc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
return $project->created_at->format('Y-m-d');
});
$data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
simplePaginate Method is exist in the path below:
Illuminate\Database\Eloquent\Builder.php::simplePaginate()

database query not working properly laravel

I have a database query as below:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->get();
echo $data["value"];
but it gives error:
Undefined index: value
if I echo $data; then I get below result:
[{"value":"theme_default"}]
get() returns a Laravel Collection object, which has magic methods to turn itself into a string when you try to use it as such (like with an echo statement). As you can see in the JSON that you've printed, $data is an array or collection of objects, so you want the first one in the collection before trying to get the value:
$row = $data->first();
echo $row->value;
Try this:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->first();
echo $data["value"];
//or
echo $data->value;
You can turn the result into an array like this:
$data = DB::table('settings')
->select('value')
->where('name', '=', $name)
->get()
->toArray();
//then use the value of the first element
dd(#$data[0]['value']);
, but I strongly suggest that you use the Laravel Collection in order to make use of its powerful methods.

Laravel use DB::table instead of ::find() to save or modify records

In my project I need to find some data from sql without using id in table. For example we can use this code to find data by id:
$result = BuyCard::find(10);
but I want to search in other table column such as user_code without changing laravel stucture instead if id with other column. I've tried this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data->result_transaction = 1;
$data->save();
For this code I'm getting an error but I can use it. But this code works fine:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data = BuyCard::find($data->id);
$data->result_transaction = 1;
$data->save();
how to edit this without using
$data = BuyCard::find($data->id);
between code? code is working fine but this is not correct.
Try to change this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
To:
$data = DB::table('buy_card_transactions')->where(array('transaction_id' => $key))->first();
Or:
BuyCard::where('transaction_id',$key)->first();

How to get table structure in CodeIgniter

I want to know the structure of a table. How I can do it in CodeIgniter. Using database class I got 'Invalid SQL Statement' error when I ran $this->db->query('desc mytable');
Try:
$fields = $this->db->list_fields('table_name');
foreach ($fields as $field)
{
echo $field;
}
From manual
For more descriptive information, you should use
$fields = $this->db->field_data('table_name');
You're going to get something like this foreach field in fields as stdClass
name = "id"
type = "int"
max_length = 11
default = null
primary_key = 1
For Get Table Schema in CodeIgniter query:
$query = $this->db->query('SHOW CREATE TABLE yourTableName');
$queryResultArray = $query->result_array();
print_r( $queryResultArray[0]['Create Table'] );

Resources