How to check and get the result if the table contain user id in laravel - laravel

I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.

If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;

Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.

Related

Wrong ID returned from local Eloquent scope

In my Laravel project I've got a model (and an underlying table) for lessons. Now I'm trying to write a local scope for returning all lessons that have been finished by a particular user. The definition of "finished" is that there exists a row in a table named "lesson_results" with this lesson's ID and the users ID.
My scope currently looks like this:
public function scopeFinished($query, User $user)
{
return $query->join('lesson_results', function($join) use($user)
{
$join->on('lesson_results.lesson_id', '=', 'lessons.id')
->where("user_id", $user->id);
});
}
This kinda works. When I do a Lesson::finished($user)->get() I get out the correct lessons for that user. However the lessons in the collection returned all have the wrong ID's! The ID's I see are the ID's from the lesson_results table. So when I check $lesson->id from one of the returned items I don't get the ID from that lesson, but the ID from the corresponding row in the lesson_results table.
I've checked in mysql and the full query sent from Laravel is the following
select * from `lessons` inner join `lesson_results` on `lesson_results`.`lesson_id` = `lessons`.`id` and `user_id` = 53
This query DO return two columns named id (the one from the lessons table and the one from the lesson_results table) and it seems Laravel is using the wrong one for the result returned.
I don't know if I'm going about this the wrong way or if it's a bug somewhere?
This is on Laravel 7.6.1.
edit: Ok, I think I actually solved it now. Not really sure though if it's a real solution or just a workaround. I added a select() call so the return row now is
return $query->select('lessons.*')->join('lesson_results', function($join) use($user)
...which makes it only return the stuff from the lessons table. But should that really be needed?
One of the same column names will be covered by the other.
Solution 1:
Specify the table with the column, and alias the other table's column if it has same column name.
Lesson::finished($user)->select('lessons.*', 'lesson_results.id AS lesson_result_id', 'lesson_results.column1', 'lesson_results.column2',...)->get();
Solution 2:
Or you can use Eloquent-Builder eager-loading whereHas,(Assuming you have build the relationship between model Lesson and model LessonResult)
public function scopeFinished($query, User $user)
{
return $query->whereHas('lessonResults', function($query) use($user)
{
$query->where("user_id", $user->id);
});
}
So you can get lesson like this:
Lesson::finished($user)->get();

Laravel Auth::user relationship

In Laravel, i´m trying to show relation elements between Auth::user (Users) and Departments. In User table i have id, name, and department_id. In Departments table I have id and name.
In user model i create
public function department()
{
return $this->belongsTo('App\Models\Department');
}
Then, in blade template I try
Auth::user()->department
But return null and doesn´t show linked departments. Null is incorrect, all users have departments. Soo, ¿Any help? ¿What´s wrong in relation?
You can try this User::with('departmento')->find(Auth::id());
This method uses less queries - the others go after the user table twice:
auth()->user()->load(['department']);
You should add 'department_id' as a second parameter ($foreignKey) when calling belongsTo method, because it will searching for departmento_id by default.
public function departamento()
{
return $this->belongsTo('App\Models\Departamento', 'department_id');
}
Or just rename User::departamento() method to User::department()
public function department()
{
return $this->belongsTo('App\Models\Departamento');
}
Relation works with Model. Auth uses the session it not uses relation
Use User Model instead
optional(User::find(Auth::id())->departmento)->department_name

Laravel Eloquent relation for getting user name for a specific id

I have a table named project. In this table I have a column named student_id. Model for this table is Project. And I have another table named user. And model name is User. Now I am retrieving all project table details in a page including student_id. Now I want to show user name instead of student_id. I mean I want to show this student name instead of student id. For example if student_id is 10 then I want to print name for that user from user table whose id is 10.
Any one please help.I have read document from laravel. But i don't know why I am not getting the eloquent concept properly.
Define belongsTo() relationship in Project model class:
public function student()
{
return $this->belongsTo(User::class, 'student_id');
}
And use it:
$project->student->name;

Eloquent relationship with 3 tables

I'm new to Stack Overflow and Laravel.
I try to develop a variable profilesystem in Laravel and I got 3 tables ('User', 'User_Fields', 'Fields').
The structure of the Fields table is following:
The structure of the user_fields table is following:
The User table is the standard table which came with Laravel 5
Now I want to get all fields from user_fields depending on which user is selected or logged in. If the user_field doesn't exists, the model should return null or create a new record for the user_field.
I tried a lot of "solutions" which came with eloquent like (hasManyThrough, belongsToMany) but I don't get the result I wanted.
Is there any solution with relationship methods?
Thanks for your help, and sorry for my bad english :/
You should be using the belongsToMany()->withPivot() to retrieve the intermediate table columns. Your user_fields is your pivot table so on your user model you should have:
class User extends Model
{
public function fields()
{
return $this->belongsToMany(Field::class, 'user_fields')->withPivot('value');
}
}
Then you can access your values for a user by:
$user = User::find($id);
foreach($user->fields as $field) {
$field->pivot->value;
}

Laravel relationship between two tables

I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.

Resources