I want to hide the columns password & OTP ,that is included in $uses result. Actually these 2 columns are part of the users table. I've tried like below. But it generates the error - Method Illuminate\\Support\\Collection::makeHidden does not exist . How to solve this? Any suggestions..
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
$d=$users->makeHidden(['password','OTP']);
return response()->json([
'message' => 'profile viewed successfully',
'data' => $d,
'statusCode' => 200,
'status' => 'success'],200);
You're trying to execute this method on the collection but it's a model method:
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
foreach($users as $user) {
$user->makeHidden(['password','OTP']);
}
And this still doesn't work since you're using DB::table('users') over Users::all().
In order to use a model, you have to do the following:
model:
class User extends Model
{
// Instead of `makeHidden()` you can do this if you want them always to be hidden
// protected $hidden = ['password','OTP'];
public function location()
{
return $this->hasOne(App\Models\Location::class, 'users.id', '=', 'location.id');
}
public function technical_details()
{
return $this->hasOne(App\Models\UserTechnicalDetail::class, 'users.id', '=', 'user_technical_details.id');
}
}
controller:
$users = Users::with(['location', 'technical_details'])
->get();
foreach($users as $user) {
$user->makeHidden(['password','OTP']);
}
Simplest solution for your case:
$users = DB::table('users')
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get()
->map(function ($user) {
unset($user->password);
unset($user->OTP);
reurn $user;
});
I'd recommend to use Eloquent Relationships instead of joins for better abstraction:
https://laravel.com/docs/8.x/eloquent-relationships
In order to get User object from db, you should use User Model:
$users = User::query()
->join('location', 'users.id', '=', 'location.id')
->join('user_technical_details', 'users.id', '=', 'user_technical_details.id')
->get();
foreach($users as $user) {
$user->makeHidden(['password','OTP']);
}
I'm late to the party, sorry.
I had the same issue. I wanted to exclude created_at and updated_at columns from my SQL result (using DB:Table, not specific eloquent models). The makeHidden function "does not exist". NoOorz24 has a similar answer to mine, but instead, I did this (which is useful if you're running a slightly old version of PHP). It's a bit more processor hungry but it did the job.
$content = DB::table($talbename)->get();
foreach($content as $c) {
unset($c->created_at);
unset($c->updated_at);
}
Related
Hello I have problem with my requests. How can I make that functions wont't return data which exist in second one. ex. user_id = 1 friend_id = 2 from sendedRequests and user_id = 2, friend_id = 1 from pendingRequests.
Here's the code :
public function showSendedRequests(){
$request = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.friend_id')
->where('who_send', $this->id)
->where('user_id', $this->id)
->where('accepted',false)
->get();
return $request;
}
public function showPendingRequests(){
$request = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.user_id')
->where([['friend_id', '=',Auth::user()->id],['accepted', '=',false],['who_send','!=',Auth::user()->id]])
->get();
return $request;
}
You can do something like this, using the <> not equal
$request = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.friend_id')
->where('who_send', $this->id)
->where('user_id','<>', $this->id)
->where('accepted',false)
->get();
return $request;
}
//for the next function
$request = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.user_id')
->where([['friend_id', '=',Auth::user()->id],['accepted', '=',false],['who_send','<>',Auth::user()->id]])
->get();
return $request;
}
For further reference
I'm using Laravel 5.4. This code retrieves users belonging to a company and return them to the client side.
The following query is used to get the user of the company
$users = User::where('company_id', '=', $idCompany)
->with([
'roles' => function($q) {
$q->whereBetween('level', [50, 999]);
}
])->get();
Situation A
return $users;
$users is an array of objects [{user1}, {user2}]
Situation B
foreach($users as $key=> $user) {
if(count($user->roles) == 0){$users->forget($key);}
}
return $users;
I remove some item from the collection and the
$users is an object of objects {{user1}, {user2}}
Removing an item from the collection seems to change the type of the variable $users
How could I remove some item from the collection while maintaining
the array of object?
EDIT
Here is the correct query
$users = User::whereHas('roles', function ($query) {
$query->whereBetween('level', [50, 999]);
})
->with('roles')
->where('company_id', '=', $idCompany)
->get();
return $users;
After manipulating the collection, you need to add ->all() to get the remaining collection;
return $users->all();
You could also do it this way
$filtered = $users->reject(function ($value, $key) {
return count($user->roles) == 0;
});
return $filtered->all();
As proposed by Alex in the comments, you could use whereHas() instead of with() to get directly all the users having a role between 50 and 999
$users = User::whereHas('roles', function ($query) {
$query->whereBetween('level', [50, 999]);
})
->where('company_id', '=', $idCompany)
->get();
stackers
I'm facing a problem on displaying data from query that contain join statement.
public function view(Request $id)
{
$user_id = $id->input('id');
$users = DB::table('users')->select('*')
->leftjoin('role_user', 'users.id', '=', 'role_user.user_id')
->leftjoin('roles', 'roles.id', '=', 'role_user.role_id')
->where('users.id', '=', $user_id)->get();
return view('/admin/view_user', ['users' => $users]);
}
From the above code, how do i display the row and the join table data from roles, and role_user
Try This :
public function view(Request $id)
{
$user_id = $id->input('id');
$users = DB::table('users')
->select('users.*','role_user.fieldName','roles.fieldName')
->leftjoin('role_user', 'users.id', '=', 'role_user.user_id')
->leftjoin('roles', 'roles.id', '=', 'role_user.role_id')
->where('users.id', '=', $user_id)->get();
return view('/admin/view_user', ['users' => $users]);
}
Write tableName.fieldName to get perticalur table's data in JOIN query
I am trying to learn how to do a query. the search field is for postcodes which are stored inside of user_profiles (and user_profiles have a relationship with users)
So I have something that returns one result (however there are more than 1) but I heard doing 2 query's for one is bad
public function index()
{
$queryUsername = Request::get('username');
$queryPostcode = Request::get('postcode');
if ($queryUsername) {
$users = User::where('username', 'LIKE', "%$queryUsername%")->get();
}
if ($queryPostcode) {
$usersInfo = UserProfile::where('postcode', '=', "$queryPostcode")->value('user_id');
$users = User::where('id', '=', "$usersInfo")->get();
}
return view('view', compact('users'));
}
for the question referenced better way is to go with join instead of two different queries
public function index()
{
$queryUsername = Request::get('username');
$queryPostcode = Request::get('postcode');
if ($queryUsername) {
$users = User::where('username', 'LIKE', "%$queryUsername%")->get();
}
if ($queryPostcode) {
$users = Users::rightJoin('user_profiles','users.id', '=', 'user_profiles.user_id')
->where('user_profiles.postcode', '=', "$queryPostcode")
->select(\DB::raw('users.*'))
->get();
}
return view('view', compact('users'));
}
if you are looking for an exact match of username
its not good to use LIKE for username matching
$users = User::where('username', 'LIKE', "%$queryUsername%")->get();
because for usernames chris and chrisgeorge and christy the query %chris% will work and you wont get the exact match so recommend to use '=' instead of like
Try with this:
public function index(){
$queryUsername = Request::get('username');
$queryPostcode = Request::get('postcode');
if ($queryUsername):
$users = User::where('username', 'LIKE', "%".$queryUsername."%")->get();
elseif ($queryPostcode):
$usersInfo = UserProfile::where('postcode', '=', $queryPostcode)->value('user_id');
$users = User::where('id', '=', "$usersInfo")->get();
endif;
return view('view', compact('users'));
}
I have a method which returns a list of provinces based on some join and where clauses. The problem I have is That laravel throws an Exception that tells there is an undefined method called whereIn. But there exist whereIn method in Eloquent. How should I use whereIn method on joins?
public static function getProvinces($IDs = array()){
$query =
DB::Table('doctors')
->join('users', function($join){
$join->on('users.id', '=', 'doctors.user_id')
->whereIn('users.status_id', array(3,4,7));
})
->join('contacts', function($join){
$join->on('doctors.id', '=', 'contacts.doctor_id')
->where('contacts.type_id', '=', 1);
})
->join('provinces', 'contacts.province_id', '=', 'provinces.id')
->select('contacts.province_id as id','provinces.name as name',DB::raw("COUNT('contacts.province_id') as count"))
->groupBy('contacts.province_id');
if(!empty($IDs))
$query->whereIn('doctors.id', $IDs);
return $query->get();
}
Thanks for your help.
Currently, JoinClause doesn't support whereIn method, but you can overwrite it following way:
$query =
DB::Table('doctors')
->join('users', function($join){
$join->on('users.id', '=', 'doctors.user_id')
->where('users.status_id', '=', 3)
->orWhere('users.status_id', '=', 4)
->orWhere('users.status_id', '=', 5);
})
->join('contacts', function($join){
$join->on('doctors.id', '=', 'contacts.doctor_id')
->where('contacts.type_id', '=', 1);
})
->join('provinces', 'contacts.province_id', '=', 'provinces.id')
->select('contacts.province_id as id','provinces.name as name',DB::raw("COUNT('contacts.province_id') as count"))
->groupBy('contacts.province_id');