Accessing data trough relationship Laravel - laravel

I have two tables/models. User and Advert.
When a user posts an advert their userid is a column in the database row. I want to use the id to get the user details and show it in a blade template.
These are the models
Advert belongs to a user.
class Advert extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
User has many adverts.
class User extends Authenticatable
{
public function advert(){
return $this->hasMany('App\Advert);
}
}
On the advert show page I want the users name and details printed out beside it. Currently I can only access the ID as that is stored as a attirbute in the advert column in the DB. How can I use this relatonship to access the users data.
This is the show controller
public function show($id){
//Shows add user clicked on based on id
$user = User::where('id', $id)->first();
$Advert = Advert::where('id', $id)->first();
return view('pages/advert/show', compact('Advert', 'user'));
}
In the show page view I can access the user id like so {{$user->id}}

You are using the $id passed into your show function for retrieving both the user and the advert.
public function show($id){
// Get the avert with the passed in id
$advert = Advert::find($id);
// From the advert get the user related to it.
$user = $advert->user;
return view('pages/advert/show', compact('advert', 'user'));
}
Take a look at https://laravel.com/docs/5.6/eloquent-relationships#querying-relations to get a better understanding of how eloquent works with relationships.

Related

How to get only selected column in a child related model?

I have two models, User and Post, where a User can have multiple Post models. In my application, I only want to retrieve the title column from the related Post model when querying for a User. Here is my current code:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Here is what I have tried to retrieve the title column for the related Post models:
$user = User::with('posts:title')-\>get();
However, this retrieves all the columns for the Post model. How can I modify my code to only retrieve the title column for the related Post models? Thank you!
try this
$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();
If you want to get the data with selected column you also need to pass the FK to identify its relationship.
The example below tells the the post also need the user_id column to identify the relationship between POST and USER model
$user = User::with('posts:title,user_id')->get();

In which Controller should I write logic for Models that are in a relationship

I am making a blog with users who each have posts. Naturally, I have a UserController, PostController, and a User and Post model.
The User model has a one-to-many relationship with the Post model like so
// User Model
public function posts()
{
return $this->hasMany('App\Post');
}
I would like to get all the posts of a specific user by using
// UserController or PostController...
$posts = User::find($id)->posts()->get()
Should I write this logic in my UserController (because it uses the User model) or should I write the logic in my PostController (because it returns posts)?
Actually, you just need to create the relationship as you did, and then you will be able call it wherever you want, just like as you described, with User::find($id)->posts()->get().
So, if you need to return a user's post on a view, for instance, you can do something like that on your UserController:
public function postsView(User $user)
{
$posts = $user->posts()->get();
return view('user.posts', compact('posts'));
}
Also, if you want the other way around (to know who is the user behind the post), you can create a relationship on your Post model using belongsTo().
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}
You can write the query anywhere in UserController or PostController
$user = User::with('posts')->whereId($id)->first();
echo '<pre>';
print_r($user->toArray());
exit;
You'll get user with all posts
In your Model User put the relationship.
public function posts()
{
return $this->hasMany('App\Post','foreign_key','local_key');
}
In your UserController or PostController get the results by using
$posts = User::find($id);
foreach($posts->posts as $post)
{
echo $post->title;
}
You can query from both controllers. From where you want to query the relationship depends on where and how you want to fetch data from.
For example, if you are showing posts related to user on a user profile page with other bio data etc then you will call the relationship in UserController.
On other hand, let's say you want to show posts related to an author on a search page then it will be better to have the posts queried via relationship in PostController.
In short, it's a choice based on convenience and optimization to be made.

How get users from section table ? laravel

The idea is that I have relation between two table's section and user
the section_id exist in users table it relation with id section
SO for ex : section_id = 2 > want to bring all users belongs to id section
My code here use id from url and I don't want to do this I want without id bring all users :
public function getAllUsers($id)
{
$data = User::where('section_id',$id)->get();
}
If I'm understanding you correctly, you want to get all the users for a particular Section that have the relationship to that section.
Assuming you have the relationship set up correctly on the Section model:
public function users() {
return $this->hasMany('App\User');
}
I suggest you go about this 'backward' and just pull the users from the Section model itself (eager loading allows one query):
$section = Section::with('users')->first();
$usersForThisSection = $section->users;
If you setup a One to Many relationship you can say things like: $user->section to return the section a user belongs to...and $section->users to get a collection of all the users in a section -- the getAllUsers() is redundant in this case.
Make sure your User and Section models contain these methods. Sounds like your migration was setup properly if you have a section_id column on your users table.
More info on one-to-many here: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
// app/User.php
class User extends Model
{
public function section() {
return $this->belongsTo('App\Section');
}
}
// app/Section.php
class Section extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}
Test out your relationships in php artisan tinker like so...
$user = User::find(1);
$user->section
$section = Section::find(1);
$section->users
you need a unique identifier to receive section_id's users. receive it from url(get) or ajax(post) . if you worry about users access then use "auth"

How to view user name by id in Laravel?

I have two table's one user and another classrooms.
Here is my user model:
public function classroom()
{
return $this->hasMany('App\classroom');
}
And here is my classroom's model:
public function user()
{
return $this->hasMany('App\User');
}
When user create classroom then i store in classroom table id, user_id, class_name, section. I already view class data in my blade page. But i can't view user name who created the classroom data.
In my view page
#foreach($classrooms as $classroom)
<li><b>Class code--><i>{{$classroom->class_code}}</i></b></li>
<li><b>Subject--><i>{{$classroom->class_name}}</i></b></li>
<li><b>Section--><i>{{$classroom->section}}</i></b></li>
<li><b>created by--><i> ???? </i></b></li>
#endforeach
My controller
$classrooms=classroomModel::where('id',$id)->get();
$posts = Status::where('class_id' , $id)->orderBy('id', 'desc')->get();
return view::make('class',compact('posts','classrooms'));
If i want to view user name who was created classroom data then what will be the right code and where should i change?
in your controller:
$classrooms=classroomModel::where('id',$id)->with('user')->first();
in your view:
$classrooms->user->name;

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...
this is my controller
class DeskController extends BaseController{
public function getDeskUsers($deskId){
$user = DeskUserList::where(function($query) use ($deskId){
$query->where('deskId', $deskId);
})->with('userName')->get(array('deskId'));
if (!$user->isEmpty())
return $user;
return 'fail';
}
this is the model
class DeskUserList extends Eloquent {
protected $table = 'desk_user_lists';
public function userName(){
return $this->belongsTo('User', 'userId')->select(array('id','userName'));
}
}
the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).
practically I want each record returned is composed of:
DeskUserList.deskId
User.userName
eg. [{"deskId":"1","user_name":antonio}]
What i get is
[{"deskId":"1","user_name":null}]
As you can see the user name is a null value...
BUT
if I edit my controller code:
->with('userName')->get(array('userId')); //using userId rather than deskId
then i get
[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]
By this way I still have two problem:
the userId field is twice repeated
I miss the deskId field (that I need...)
hope be clear, thanks for your time!
You need belongsToMany, no need for a model representing that pivot table.
I assume your models are Desk and User:
// Desk model
public function users()
{
return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}
// User model
public function desks()
{
return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}
Then:
$desks = Desk::with('users')->get(); // collection of desks with related users
foreach ($desks as $desk)
{
$desk->users; // collection of users for particular desk
}
// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Resources