I want to bring all the columns from laravel at once - laravel

The "users" table contains the name, age, and addr columns. If I want to print these three columns, I need to do something like this:
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name.",";
echo $user->age.",";
echo $user->addr."<br>";
}
I want to output all the columns, even if not each. So I tried this.
$users = DB::table('users')->get();
foreach ($users as $user) {
print_r($user);
}
result.
App\Model\Users Object
(
[timestamps] =>
[connection:protected] => mysql
[table:protected] => main_settings
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
......
I did not get the result I wanted. How can I display all the columns at once?

After registering the question, I found the answer.
$users = DB::table('users')->get()->toArray();
foreach ($users as $user) {
print_r($user);
}
Using toArray () gives me the result I want.

I suggest you to make use of model in laravel to add/edit/delete/fetch data.
you can try the below code for fetching the user table data.
$users = App\User::all();
foreach($users as $user) {
dd($user);
}
Note : use User model in your class before accessing it.
If you want to fetch data using SQL Raw query then try the below code.
$users = DB::table('users')->get();
foreach ($users as $key=>$user) {
dd($key,$user);
}

Related

Laravel 5 with eloquent relation callback function returning wrong records

Here is User Model
public function userpackages()
{
return $this->hasMany('App\UserPackages');
}
Trying to get users packages form specific month and year but it returning all records.
$users = User::with(['team', 'userpackages' => function($package) use($month,$year) {
$package->whereMonth('created_at', $month)->whereYear('created_at', $year);
}])->get();
Fetching
foreach ($users as $key => $user) {
$userpackages = $user->userpackages;
}
If I'm understanding correctly, you are filtering the eager load, but this does not affect the models returned. You need to repeat the filter using whereHas() to limit the models that are returned. In addition, functions like whereDate() can be very inefficient, especially if the column is indexed. I suggest using whereBetween() when searching a date range.
$date = Carbon::createFromFormat("Y-m", "$year-$month");
$range = [$date->startOfMonth(), $date->endOfMonth()];
$users = User::with('team')
->with(['userpackages' => fn ($q) => $q->whereBetween('created_at', $range)])
->whereHas('userpackages', fn ($q) => $q->whereBetween('created_at', $range)
->get();
To explain further:
User::with('userpackages') returns all users, each with all of their packages.
User::with(['userpackages' => 'some condition']) returns all users, each with some of their packages
User::whereHas('userpackages', 'some condition') returns some users, each with all of their packages
User::(['userpackages' => 'some condition'])->whereHas('userpackages', 'some condition') returns some users, each with some of their packages.

Order by count of column in laravel 5.5 using eloquent orm

I am trying to set order by clause on count of field inside of larvel model.
I am using mongodb with Eloquent.
Is it even possible?
Here is a quick snippet of the query I am trying to run:
$books = Books::where(function ($query) use ($params, $res) {
$query->where('labels', 'elemMatch', array(
'genre' => $res->genre,
'outdated' => $res->false
))
->where('available', true)
->where('isSelling', true);
})
->orderBy('reviews','desc')
->paginate($params['limit']);
Reviews is an array in my database
Is it possible to order by the count of it?
you can try doing this
$books = Books::where(function ($query) use ($params, $res) {
$query->where('labels', 'elemMatch', array(
'genre' => $res->genre,
'outdated' => $res->false
))
->where('available', true)
->where('isSelling', true);
})
->orderBy('reviews','desc')
->get();
// sorting the books using sortBy or sortByDesc
$books = $books->sortByDesc(function($book){
return count(json_decode($book->reviews)); // we return the count of the reviews here
}
// get sorted ids of the books
$ids = $books->pluck('id')->toArray();
// we get the books paginated with the ids order
$books = $books->whereIn('id',$ids)
->orderByRaw(\DB::raw("FIELD(id, $ids)"))
->paginate($params['limit']);

Laravel eloquent relation search using child table record

Problem :
I want only that records where relational records [ user ] not null.
In my case I want only first record. where user is not null
Result:
User Table
id
name
email
Project Tabel
id
title
user_id [foreign key]
My code is like this
$projects = App\Project::with(['user' => function ($user) {
$user->where('name', '=', 'Ketan');
}])
->get();
foreach ($projects as $project) {
echo $project->title.' - '.$project;
}
My result is like this :
The below code is working
$projects = App\Project::whereHas('user', function ($user) {
$user->where('name', '=', 'Ketan');
}])->get();
Change 'with' to 'whereHas' and note that whereHas doesn't accept the array as the param
For reference Laracasts Link
I got solution of my question
$projects = App\Project::whereHas(['user' => function ($user) { <--Change Here
$user->where('name', '=', 'Ketan');
}])
->get();
Only Change 'with' to 'whereHas'
By this solution, I have got only those Project records in which user ( relational record ) is not null.
You can try:
$projects = App\Project::with(['user' => function ($user) {
$user->where('name', '=', 'Ketan');
}])
->get();
foreach ($projects as $project) {
if($project->user != null){
echo $project->title.' - '.$project;
}
}

Laravel maatwebsite import and fill a column with a select form

I'm using maatwebsite's Excel import library to import employees into a database table and it works quite well. However, on the View page where I select the Excel file to import, I have a select drop-down that shows data from the related Companies table, so that that specific selected Company is posted to all the currently imported employees' Comp_id foreign key. I have created the hasMany and belongsTo relations in the respective Company and Employee models.
The data sent in the EmployeeController:
public function viewImport()
{
$employees = Employee::all();
return view('viewImport',
['companies' => Company::pluck('CompanyName', 'Comp_id')
])->withEmployees($employees);
}
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
$company = Company::.....; /*???????????????
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['name'=> $v['name'],
'surname'=> $v['surname'],
'idno'=> $v['idno'],
'phone'=> $v['phone'],
'salary'=> $v['salary'],
'dob'=> $v['dob'],
'jobdescription'=> $v['jobdescription'],
'initials'=> $v['initials'],
'Comp_id' => .... /* ???????????????
];
I've included the Company model as class in the EmployeeController.
I want to add a field insertion 'Comp_id' => .... with the Comp_id value of the selected drop-down. How do I create the $company variable in the function so that the selected Comp_id can be inserted for every row? Or is there a completely different way?
Thanks in advance.
Nailed it with 'comp_id' => $request->get('Comp_id').
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['name'=> $v['name'],
'surname'=> $v['surname'],
'idno'=> $v['idno'],
'phone'=> $v['phone'],
'salary'=> $v['salary'],
'dob'=> $v['dob'],
'jobdescription'=> $v['jobdescription'],
'initials'=> $v['initials'],
'comp_id' => $request->get('Comp_id'),
];
assuming your view has a form with a select with your Comp_id, you should be able to grab it from your incomming request:
$company->comp_id = $request->get('Comp_id');
just a hint: have a look at laravel's mass assignment feature.

Can't return object with belongsToMany relationship attached

I'm trying to return a list of $users with an array of roles.
Here's my controller:
$users = DB::table('users')->take(5)->skip(2)->get();
foreach ($users as $user)
{
$user = User::with('roles')->find($user->id);
}
return Response::json(array(
'users' => $users
));
And here's the model relationship:
public function roles()
{
return $this->belongsToMany('Role')->withTimestamps();
}
But this just returns the users without the role attached to it. However, if I do this:
return Response::json(array(
'users' => User::with('roles')->get()
));
I get the full list with the roles attached to each user. So, what am I doing wrong?
Oddly, if I do this:
return Response::json(array(
'users' => User::with('roles')->find($user->id)
));
Then it returns that user with the roles as I expected, so why not return it in the foreach statement?
You are loosing the whole Eloquent relations functionality when using DB queries.
You could just
$users = User::with('roles')->take(5)->skip(2)->get();
A good practice is to not mix Eloquent model "style" queries (User::...->get()) with direct DB queries (DB::table('user')...->get).
The foreach uses pass by value. That means you are not changing the actual array item but just a copy of the value. To change that and get the item passed by reference add a &:
foreach ($users as &$user) {
$user = User::with('roles')->find($user->id);
}
However why don't you just do it this way?
$users = User::with('roles')->take(5)->skip(2)->get();
return Response::json(array(
'users' => $users
));

Resources