Laravel Eloquent Results Not coming in find all query - laravel

I created a Laravel Eloquent Query With all
$result = Model::all()
but when it returns only empty object return as result records are there in the table

when I used
var_dump();die;
instead of
dd();
the result coming perfectly it is something with the
dd();
display

Related

How to know what columns are presents in a Eloquent query before to execute it in Laravel 5.5?

Im using Laravel 5.5 and I have and QueryBuilder object (from the "Illuminate/Database/Eloquent/Builder" class).
I want to set an orderBy sentence into my query, but only if this field is present and exists in the QueryBuilder object (as column in the select section sentence).
For example, there is an User model, with the following fields ['id', 'firtsname', 'lastname', 'username','description'].
This is my object:
Use App\User;
$query = User::query();
if ($request->input('sort') != null) {
$model_query->orderBy($request->input('sort'), 'ASC');
}
$users = $query->get();
When I execute it, works fine (if I send you consistent data, of course). But if I set a column what does not exists, it sends and exception. So, the question is, how I can get the columns to retrieve from my $query object? To validate it, and if it's presents, execute the ordening code.
To answer your question, you can get the presence status of a column using Schema::hasColumn()
if (Schema::hasColumn('users', $request->sort)) {
//
}
GOING FURTHER
Now this doesn't seem very efficient, and maybe potentially leak data. Better validating your sort input and accept only proper column names:
$request->validate(['sort' => 'in:column1,column2']);

How to get all records which meet a Criteria in Laravel Tinker?

I can get the first user, who is an admin in Laravel's tinker using the following command:
$adminUser = App\User::where('is_admin',true)->first();
How do I get all the users which meet this where criteria?
Just change first() to get().
$adminUser = App\User::where('is_admin',true)->get();
first() is used when you want to retrieve single row or column. where get() is used to retrieve all rows.
just go through the laravel official documentation database query builder section here. It will give you information regarding most of every possible things you can playoff with laravel.
$users = App\User::where("is_admin", true)->get();
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object. You may access each column's value by accessing the column as a property of the object:
foreach ($users as $user) {
echo $user->name;
}
Src: https://laravel.com/docs/5.6/queries
In case of Tinker, things in Query builder and Eloquent docs will work in Tinker. It exists for the purpose of instantly getting the result without debugging using your real application.
The first() function is used when you want to retrieve single row, whereas the get() function is used to retrieve all matching rows.
$adminUser = App\User::where('is_admin', true)->get();
dd($adminUser);

Use Laravel 5.3 Query Builder to replicate Eloquent ORM data structure for Sub Query

I am trying to replicate the result set that I get when using Eloquent ORM, except with Laravel Query Builder. Basically using this code I can get the packs to appear nested within the products so that when I loop them on the view I can further loop the packs within each products. Seems pretty basic right (see result set below).
$get_posts_for_product = Product::where('active', 1)
->with('packs')
->get()->toArray();
I have tried a few ways using Query Builder to get this to work but it joins the packs inline as I thought it would.
What is the best way to get this same Array structure using Query Builder, I am aware that the result set is a different type of array and that is fine but for my project it must be done using Query Builder at this point.
Thanks.
I would say, that is why you have Eloquent: you don't have to worry about how to have those relationships together.
However incase you really want to achieve the same result I will demo this using two tables users and messages:
1st method:
Retrieve the users and transform it by querying the database for relationships:
$result = DB::table('users')->get()->transform(function ($user){
$user->messages = DB::table('messages')->where('user_id', $user->id)->get();
return $user;
});
Downside: Having many users means a lot of db query on messages table.
Upside: less codes to write
2nd method:
Retrieve both tables using all the ids of user to query the messages:
$users = DB::table('users')->get();
$messages = DB::table('messages')->whereIn('user_id', $users->pluck('id')->toArray())->get();
$result = $users->transform(function ($user) use ($messages){
$user->messages = $messages->where('user_id', $user->id)->values();
return $user;
});
Downside: The need to still transform it.
Upside: Less database trips. i.e two queries only.
3rd method
Looks like the second except that you can group messages by 'user_id' then you do no extra filter when transforming users result:
$user = DB::table('users')->get();
$messages = DB::table('messages')->whereIn('user_id', $user->pluck('id')->toArray())
->get()
->groupBy('user_id');
$result = $user->transform(function ($user) use ($messages){
$user->messages = $messages[$user->id];
return $user;
});
Downside: Same with two.
Upside: no extra filter when transforming users.
Other method
Join on both users and messages when querying then transform the response, or simply use it as it is.
PS: Eloquent uses query builder.
The answer is open for update.

Don't paginate the results

The following is the query I am using to get the results from the database. As you can see it has a chain paginate. I don't want my results to be paginated.
return DB::table('example')->where('status', '1')->orderBy('name', 'desc')->paginate(50);
When I remove the method paginate.
return DB::table('example')->where('status', '1')->orderBy('name', 'desc');
I get the following error message.
Object of class Illuminate\Database\Query\Builder could not be
converted to string
How can I do that?
Paginate is one of several methods that execute the query. When you remove it you still have an unexecuted query builder. To execute the query without paginating simply use get()
return DB::table('example')->where('status', '1')->orderBy('name', 'desc')->get();

About the laravel eloquent model

The laravel API document: Illuminate\Database\Eloquent\Builder::first() description that:
Model|Builder|null first(array $columns = array('*'))
Execute the query and get the first result.
Parameters
array $columns
Return Value
Model|Builder|null
I can't understand the mean of the return value, In which case it will return Model and In which case it will return Builder?
When you have used eloquent model for retrieving first record it return response in Model, and not sure about builder but when you retrieve records using builder it return builder object.
for example, consider we have states table and we are going to retrieve first record using two different method
1) Query Builder
$state_builder = DB::table("states")->first();
2) Eloquent Model
$state_eloquent = State::first();
you can check the difference between both response, and when no record found it will return null.

Resources