Laravel 5 nested relationship - laravel

I have 3 tables, with:
User: id | name
Products: id | name | user_id
Tracks: user_id | product_id
Relationships between these models (tables) are:
//User.php*************************************************
public function products() {
return $this->hasMany('App\Product');
}
public function track() {
return $this->hasMany('App\Track');
}
//Product.php*************************************************
public function user() {
return $this->belongsTo('App\User');
}
public function track() {
return $this->belongsTo('App\Track');
}
//Track.php*************************************************
public function products() {
return $this->hasMany('App\Product');
}
public function user() {
return $this->belongsTo('App\User');
}
Track table is used if user want to track the product. Some kind of bookmark.
So, when I'am on product page, $product = App\Product::find(1), if I want to echo the user name, I do $product->user()->name, but if I want to know if the user already tracking the current product, when I do $product->user()->track()->get() I receive this error:
Call to undefined method Illuminate\Database\Query\Builder::track()
If I do $product->user()->with('track')->get(), I don't get an error, but I get User Object which it do not contain info if the user already tracking the product.
How can I know if user is already tracking the product?

First, some of your relationship should be like these
Product.php
public function track() {
return $this->hasMany('App\Track');
}
Track.php
public function product() {
return $this->belongsTo('App\Product');
}
now to check if a user is tracking a product
$product = App\Product::find($id);
$product->user->track()->where('product_id', $product->id)->first();
another way
$user = App\User::find($id);
$user->track()->where('product_id', $product->id)->first();
And to check if logged in user is tracking the product, you can get the logged in user by Auth::user() , so
$user = Auth::user();
$user->track()->where('product_id', $product->id)->first();

Related

Laravel One to Many relation with 2 primary keys

I've 2 tables
Users table
id
name
...
Chats table
id
from_id // fk - id on users, the user sent the message
to_id // fk - id on users, intended user
message_body
Now, I'm trying to set up One to Many relation where user has many chat messages but a chat message has two user. from and to user
How can I define this relationship?. I have to user eager loading.
I tried to use Compoships but it didn't work.
My code
User Model
public function chats() {
return $this->hasMany(Chat::class, ['from_id', 'to_id'], 'id');
}
Chat Model
public function user() {
return $this->belongsTo(User::class, ['from_id', 'to_id'], 'id');
}
public function chats() {
return $this->hasMany(Chat::class, 'from_id', 'id') + $this->hasMany(Chat::class,'to_id','id');
}
public function userFrom() {
return $this->belongsTo(User::class, 'from_id', 'id');
}
public function userTo() {
return $this->belongsTo(User::class, 'to_id', 'id');
}
Why don't you do something like that?
On your User model, set up two relationships like this:
public function chatsFrom() {
return $this->hasMany('App\Chat', 'from_id');
}
public function chatsTo() {
return $this->hasMany('App\Chat', 'to_id');
}
Then, on your Chat model, also set up two relationships, one to from and another to to, both referencing a User model. Like this:
public function fromUser() {
return $this->belongsTo('App\User', 'from_id');
}
public function toUser() {
return $this->belongsTo('App\User', 'to_id');
}
This way, you can access the relationships using something like this:
$user->chatsFrom();
$user->chatsTo();
$chat->fromUser();
$chat->toUser();

Updated: Why relationship works when user is Admin, but won`t when Regular user?

I have 3 models: User, Role and Currency. I am confused about relationship between them.
Then User is Admin this works:
Auth::user()->currency->symbol)
When regular User I get error:
Trying to get property of non-object
if dd(Auth::user()) it show user, but cant access to relationship with model Currency. Why it is so?
User model relationship:
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id');
}
Currency model relationship:
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
If you need extra information, let me know.
User model
public function currency()
{
return $this->belongsTo(Currency::class);
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id');
}
Going with an assumption that your User model has an attribute currency_id
$this->belongsTo(TABLE, FORIEGN KEY, TABLE KEY);
refer this
User model
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id', 'id');
}
Currency model
public function users()
{
return $this->hasMany(User::class, 'created_by_id', 'id');
}

Laravel eloquent hasmany->hasmany

it is possible to get all details (user, posts, postimages) within one collection / json?
user->hasmany(posts)
post->hasmany(postimage)
user:
id | name
post:
id | user_id | text
postimage:
id | post_id | imgpath
user model:
public function posts() {
return $this->hasMany('App\posts')->orderBy('id', 'ASC');
}
posts model:
public function images(){
return $this->hasMany('App\postsimages');
}
get all posts from user works fine:
$myposts = users::find(Auth::user()->id)->posts;
i'm able to get all images from a post within a loop
foreach($myposts as $mypost) {
$postimages = $mypost->images;
}
what i want is to get all posts, images without the loop e.g
$myposts = users::find(Auth::user()->id)->posts->images
thanks
Yes, use hasManyThrough relationship.
posts model:
public function images()
{
return $this->hasMany('App\postsimages');
}
user model
public function posts()
{
return $this->hasMany('App\posts')->orderBy('id', 'ASC');
}
public function images()
{
return $this->hasManyThrough('App\posts', 'App\postsimages');
}
then
$postimages = Auth::user()->images;

Need help laravel 4.2

I want to get the username in table user, of post ID in post table and return View::make('post.index'). I need to view in post.index blade.
Database
users table
id
username
post table
id
message
posts_id
Post.php #models folder
public function posts()
{
return $this->belongsTo('User');
}
User.php #models folder
public function post()
{
return $this->hasMany('Post');
}
PostController.php #controller folder
public function index()
{
$posts = Post::with('username')->get();
return View::make('post.index')->with('posts', $posts);
}
post/index.blade.php
the result here
i need to the result of author id become the username
for the best practices:
your model class names should be User and Post. database table names should be users and posts.
in Post.php file ,
public function user()
{
return $this->belongsTo('User');
}
in User.php file,
public function posts()
{
return $this->hasMany('Post');
}
in your PostController.php
public function index()
{
$user_of_the_post = Post::find(postId)->user; //replace the postId //this will return the user object of the specified post
$user_name_of_the_author = $user_of_the_post->username;
**pass the necessary data to the view and print and return the view**
}

Laravel Eloquent hasMany and BelongsToMany not returning using with

I am trying to do a single query to get back an order and the card to charge, but getting an error.
Card model:
class Card extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function orders()
{
return $this->hasMany('Order');
}
}
Order model:
class Order extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function card()
{
return $this->hasOne('Card');
}
public function address()
{
return $this->belongsTo('Address');
}
public function orderItems()
{
return $this->hasMany('OrderItem');
}
}
What I am trying to get back:
$order = Order::with('card')->find($id);
This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.
Any idea how I can get back the order with the card/token details?
DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.
Orders table basically:
id | card_id
Cards table:
id | token
Trying to get the token col to return with the Order.
In your Order model, you need to change this:
public function card()
{
return $this->hasOne('Card');
}
to this:
public function card()
{
return $this->belongsTo('Card');
}
The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.

Resources