I am new to laravel so can anybody explain me that what exactly get() function of eloquent ORM does. I have following query and I need to know on which line the database is queried.
$propertiesQuery = Property::with('country', 'city','bannerInvoicesCount','rejectedBannerInvoicesCount')
->where('is_deleted','=',1);
if(Auth::user()->type == 'po') {
$propertiesQuery->where('user_id', '=', Auth::user()->id);
}
$propertiesQuery->orderBy('created_at', 'DESC');
$properties = $propertiesQuery->get();
Now in above code I have accessed Model once whether that is the point when db is queried or when I have called get() function. I am not been able to comprehend the internal working of this. That exactly on which statement the query is executed.
#Raza before eloquant $propertiesQuery->get() step, it prepare your query like:
select * from table where user_id=1
and when you call/trigger the $propertiesQuery->get() method, it forward your query to database and fetch the records against your query. like, normally we do in plain sql:
eg: mysql_query($query);
then mysql_fetch_assoc() etc methods
so get() method contains on: execute the query and return all the records in the array format.
I hope it will help you.
Related
I have a problem with laravel
I want to use a query result in my controller with a if clause to manage what i return to the view.
$res = Chaussures::where('id',$id);
if($res->name=='Adidas'){
return...
}
else {
return...
}
I tried this but it didn't work
You need to execute the query to get the result first. Then you can do whatever you need with the data.
$res=Chaussures::where('id',$id)->first();
Searching for models by ID is such a common task that Laravel has a method called find() to make it easier. This line does the same as the above.
$res=Chaussures::find($id);
I'm trying to query records using a parameter from a route, but it's not working properly.
This is my route:
Route::get('reports/{id}', 'ReportsController#show');
This is my controller method:
public function show($id) {
return Reports::all()->where('user_id', $id);
}
When accessing the route 'reports/1', it returns nothing. However, if I hardcode in the id to use in the method, it does work:
public function show($id) {
return Reports::all()->where('user_id', 1);
}
I don't know what is wrong with my code, please help.
Your issue is that you're calling where() on a Laravel Collection, not on a Laravel Query Builder.
Reports::all() will run a query that will get every single report from the database and put it into a Collection. You're then running the where() method on that Collection.
The difference is that the where() method on a Collection loops through the items in the collection, and does a strict comparison (===), whereas the query builder adds a parameterized where clause to the SQL, which doesn't care about the variable type.
What you're running into is that when using the variable, you're running where('user_id', '1'), which is doing a strict comparison (===) of the user_id field to the string '1'. Since all the user ids are integers, you won't get any results.
What you really want to do is add your where conditions to the SQL statement. Instead of your current logic, you want:
public function show($id) {
return Reports::where('user_id', $id)->get();
}
This will fix your issue, as well as only return those records that match your where clause, which may severely boost your performance. If you have a million reports, you don't want to build a collection of a million objects, and then iterate through them.
I am encountering a strange issue in Laravel.
The below is an index function in one of my controllers.
public function index($merchant_url_text)
{
//
$deals = DB::table('tbl_deal')
-> join ('tbl_merchant', 'tbl_deal.merchant_id', '=', 'tbl_merchant.merchant_id')
-> where ('merchant_url_text', $merchant_url_text) -> toSql();
//return $merchant_url_text.$deal_id;
dd($deals);
//return $merchant_url_text;
}
As you can see I am passing merchant_url_text from route.
Route::get('/testroute/{merchant_url_text}', ['uses' =>'dealsVisibleController#index']);
When I am trying to debug the query by printing it, I am getting
"select * from `tbl_deal` inner join `tbl_merchant` on `tbl_deal`.`merchant_id` = `tbl_merchant`.`merchant_id` where `merchant_url_text` = ?"
This means that the query builder is not reading the $merchant_url_text variable. However, when I return just that variable, it is being printed.
Just can't figure out why the query builder is not able to include the $merchant_url_text variable in the query when it is available in the index function.
Any suggestions.
I am pretty sure that your code is correct. The SQL output function toSql() does not show the values of variables and only prints out a ? for security reasons.
You may access all your queries by using
$queries = DB::getQueryLog();
It is also printing the query parameters as array.
To get the last query:
dd(end($queries));
To disable the log:
DB::connection()->disableQueryLog();
See the docs for further information.
I would like to know if it's possible to return a MySQL stored procedure call as an eloquent object.
The below call works fine for me, but $result always returns an array instead of the usual Eloquent object.
$result = DB::select('call bookings_by_voucher()');
Does anyone know how to return this as an object, so that I can use ->count(), ->get() etc.
You must pass the array into a new instance of your eloquent object.
$booking = new Booking($result);
A late question, but if anyone else needs this:
Booking::fromQuery('call bookings_by_voucher()');
The only problem is you can't do further sql operations like where, limit, etc, since you can't manipulate a stored procedure directly, eg: you can't do "call bookings_by_voucher() where active = 1 limit 200". You can use laravel collection operations though.
https://laravel.com/docs/5.4/eloquent-collections
you can use eloquent MODEL. It return an object .
ex.
$user = app\ModelName::all()->count();
get(),count() and other aggregate function works with Models
I see you can call my MyModel::all() and then call "where" "groupBy" .. etc
I cant seem to find orderBy as this Q & A suggest..
Has this been removed in Laravel 5?
I've tried looking through the docs for a reference in Collection and Model but I'm assuming these are actually just modifiers for the collection returned and not actually modifying the query statement..
The only way I know of using order by is
\DB::table($table)->where($column)->orderBy($column);
Is that the only way to order your database select when executing a query?
You can actually just use it like where and groupBy:
$result = MyModel::orderBy('name', 'desc')->get();
Note that by calling MyModel::all() you're already executing the query.
In general you can pretty much use every method from the query builder documented here with Eloquent models. The reason for this is that the model proxies method calls (that it doesn't know) to a query builder instance:
public function __call($method, $parameters)
{
// irrelevant code omitted
$query = $this->newQuery();
return call_user_func_array(array($query, $method), $parameters);
}
$this->newQuery() creates an instance of the query builder which then is used to actually run the query. Then when the result is retrieved the model/collection is hydrated with the values from the database.
More info
Eloquent - Laravel 5 Docs
Illuminate\Database\Eloquent\Builder - API docs
And also the regular query builder (since quite a few calls get passed from the eloquent builder)
Illuminate\Database\Query\Builder - API docs
You can achieve this with the following solution:
$result = ModelName::orderBy('id', 'desc')->get();
You can do it by using sort keys
Model::all()->sortKeys()
(or)
Model::all()->sortKeysDesc()