I am doing project in laravel.
Database Table 1
user_verification
------------------------------------------
'id', 'user_id', 'verified', 'verified_by'
Database Table 2
user
-----------------------------
'id', 'name', 'email', 'pass'
I want to get data as all users which are verified('verified' = 1) and name of user('verified_by' is user id from user table) who does verification.
My controller method is like,
public function verifiedProviders(){
//$user_data = sql query goes here...
return view('display',compact('user_data '));
}
for example:,
I want to display in blade file as follow
name:abc,
email:abc#gmail.com,
verified by: name (id present in *verified_by* field) from *user* table.
I am not getting how to get and display this data in laravel's blade file. How to use relationships eloquent method or database query. Thanks in advance.
User::select('name', 'email', 'u2.name as verified_by_name')
->join('user_verification', 'user_verification.user_id', '=', 'user.id')
->join('user u2', 'user_verification.verified_by', '=', 'u2.id')
->all(); // I guess
Of course you may want to limit your query to return only the first 25 results and display them, etc.
References:
https://laravel.com/docs/5.2/queries#joins
https://laravel.com/docs/5.2/queries#selects
Related
I have one to many polymorphic relationship in Laravel and I am trying to fetch data using eloquent query. I have Favorite model with favorites table
id user_id favoritable_id favoritable_type
1 17 1 App\Models\ProfileImage
2 10 1 App\Models\PostVideo this is some other model
and profile_images table with
id user_profile_id title path
1 17 etc etc
I need to fetch all profile_images from profile_images table that correspond to data in favorites table. So id from profile_images to match favoritable_id, user_profile_id to matches user_id and favoritable_type to match App\Models\ProfileImage from favorites table. Any help is appreciated. Here is my code.
Controller
public function getProfileImages()
{
$profileimage = ProfileImage::whereColumn('id', 'favoritable_id')->first();
// I AM BASICALLY STUCK HERE WITH $profileimage !!!
$favoriteProfileImages = $profileimage->favorites()->where([
'user_id' => auth()->id(),
'favoritable_id' => $profileimage->id,
'favoritable_type' => ProfileImage::class
])->get();
return $favoriteProfileImages;
}
Option 1
Assuming that there is no relation between User and Favorite models, get all the PostImage records which have an entry in favorites table for the currently logged in user.
$profileImages = Favorite::where('user_id', auth()->id())
->with([
'favoritable' => fn($query) => $query->where('favoritable_type', ProfileImage::class)
])
->get()
->pluck('favoritable')
->flatten()
->all();
Option 2
Assuming that User hasMany Favorite records - hasMany relationship exists
class User extends Model
{
public function favorites()
{
return $this->hasMany(Favorite::class);
}
// ...rest of the class code
}
Get the results via the User model
$profileImages = User::with([
'favorites' =>
fn($query) => $query->where('favoritable_type', ProfileImage::class)->with('favoritable')
])
->where('id', auth()->id())
->first()
->favorites
->pluck('favoritable')
->flatten()
->all();
I have many to many relationship. In postman I pass find_id and status.
My query is like: UPDATE finds_user SET status = TRUE WHERE find_id = 2 AND user_id = 1.
I do it now like that:
DB::table('finds_user')
->where('find_id', '=', $request->find_id)
->where('user_id', '=', $user->id)
->update(['status' => $request->status]);
How I can do it with Eloquent instead of DB Query Builder?
Thank you a lot!
we have tow condition for update:
1- find_id = 2
2- user_id = 1.
suppose the relation name in the user model called 'finds'
the query will look like this:
User::find(1)->finds()->newPivotQuery()->where('find_id',2)->update(['status'=>true])
and if you have a model for the pivot table with name like "FindUser":
FindUser::where('user_id',$user->id)->where('find_id',2)->update(['status'=>true]);
In my application, there's two tables at the moment: users and employees. The latter is simply a profile table for the boilerplate users table that ships with Laravel.
I have two foreign keys inside of employees, one is user_id that points to id on users table. So basically, the profile data of the registered user. The second foreign key in employees is manager_id. That is the id of the person who is the manager of an employee. Some users are managers and have a blank manager_id field.
I want to retrieve the row from my Employee model where the user_id matches the manager_idand then send them all to my view, where they will see the first_name and last_name of the manager. At the moment I see the manager ID instead of their name.
Sample LeftJoin =>
DB::connection('testing')->table('table1 as t1')
->select('t1.column, t2.column')
->leftJoin('table2 as t2','t2.client_id','=','t1.id')
->get();
Try some thing like this:
$users = DB::table('users t1')
->join('users t2', 't1.id', '=', 't2.user_id')
->select('your column list')
->get();
// here we are creating 2 aliases for users table which make it self join
In your Employees model add the following method:
public function manager()
{
return $this->hasOne('App\User', 'id', 'manager_id');
}
You can then get the name of the Manager like this:
$employee = \App\Employee::find(1);
$manager = $employee->manager()->first();
$manager_name = $manager->name;
I'm trying to fetch following things from the database:
user name
user avatar_name
user avatar_filetype
complete conversation_messages
with the following query:
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
It works fine so far, but the avatar's column name is 'name' like the column name from the 'users' table.
So if I'm using this query the to get the output via $conversation->name, the avatar.name overwrites the users.name
Is there a way to rename the query output like the mysql "as" feature at laravel 5.1?
For example:
$conversation->avatarName
$conversation->userName
Meh okay.. i've found a simple solution here
->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
As you can mention I've added the requested "as-Feature" next to the table.columnName
Take a look at this example of trying to join three tables staffs, customers and bookings(pivot table).
$bookings = \DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')
->with('bookings', $bookings);
I had the following problem, simplified example:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
$result is a collection of Donation models. BUT CAREFUL:
both tables, have a 'created_at' column. Now which created_at is displayed when doing $result->created_at ? i don't know. It seems that eloquent is doing an implicit select * when doing a join, returning models Donation but with additional attributes. created_at seems random. So what I really wanted, is a return of all Donation models of the user with email hello#papabello.com
solution is this:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
Yeah, simply rename the column on either table and it should work.
Also what you can do is, rename the user.name column to anything, also rename sender column of conversation_messages to id and perform a natural join.
I have a table Registrationrequests where I have course_id and user_id and some other field.
$users_id = Registrationrequest::where('course_id', $query_course_user)->where('registered', 1)->get();
From the above query it gives me an array of result. But I need to take the details of these user_id from another table Users. I'm using Laravel. Table models are Registrationrequest and User
How can I get the user details from the above select result? I'm not that good in Joins. Any advice?
Use Eloquent's whereHas method:
$courseId = Request::get('course_id');
$users = User::whereHas('registrationRequests', function($query) use ($courseId)
{
$query->where('course_id', $courseId)->where('registered', 1);
});
This assumes you have set up the proper relationship in your User model. If not, add this method to your user model:
public function registrationRequests()
{
return $this->hasMany('Registrationrequest');
}