How to retrieve data? - php

Post Model
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users()
{
return $this->belongsTo('App\User');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
Comment Model
class Comment extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
}
Tag Model
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Tag');
}
User Model
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
Now my question is how i can access all comments that belong to post with commented username and tags belongs to that posts.Even i have confusion regarding tag relation because its having many to many relation
Thank you

Tag Model
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Tag');
// Should this be return $this->belongsToMany('App\Post');
}
Now solution for your question is "EAGER LOADING", let's see how we can use it for your situation.
1. All Comments
$commentsCollection = Comment::all();
// this will give us all comments.
2. Post With Comments and Users and tags
$postsCollection = Post::with('comments','users','tags')->get();
// this will give you collection of post with comments, users and tags.
//So here you have all tags that belongs the a particular post.
Missing Relation
You are missing relation between Users and Comments.
Modified Comment Model
class Comment extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Modified USER Model
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
public function comments()
{
return $this->hasMany('App\Comment');
}

Related

What if you make Model for pivot table in Many To Many relationship

I have made a separate Model and defined the required relationships between all my Many To Many Models:
class AttributeProduct extends Model
{
use HasFactory;
protected $table = 'attribute_product';
protected $guarded = [];
public function attribute()
{
return $this->belongsTo(Attribute::class, 'attribute_id', 'id');
}
public function product()
{
return $this->belongsTo(Product::class, 'product_id', 'id');
}
public function value()
{
return $this->belongsTo(Value::class, 'value_id', 'id');
}
}
For example, this Model is connected to attribute_products table.
And then I added this method to Product model:
public function attributeproducts()
{
return $this->hasMany(AttributeProduct::class, 'product_id', 'id');
}
So I wonder if it is good to make a separate model and add my own methods to it or I should use Laravel pre-defined way?

Laravel 5 Three-way One-to-Many Eloquent Relationship

I have database like this
opportunities
Id
contact_id
contacts
Id
User_id
users
id
User model :
class User extends Authenticatable
{
public function Contact()
{
return $this->hasMany('Customer\model\Contact');
}
}
Contact model:
class Contact extends Model
{
public function Opportunity()
{
return $this->hasMany('Sale\Model\Opportunity');
}
public function User()
{
return $this->belongsTo('App\User');
}
}
Opportunity model
class Opportunity extends Model
{
public function Contact()
{
return $this->belongsTo('Customer\Model\Contact');
}
public function User()
{
return $this->hasManyThrough('App\User','Customer\Model\Contact','user_id','id');
}
}
When on controller
$Opportunity = Opportunity::with('User')->paginate(10);
print_r($Opportunity->User);
Show me wrong data.

Why am I getting next error: Trying to get property of non-object? laravel

class Article extends Model
{
protected $fillable = ['category_id','author_id','title','img','description','text'];
public function user()
{
return $this->belongsTo('App\User');
}
public function article_category()
{
return $this->belongsTo('App\ArticleCategory');
}
}
class ArticleCategory extends Model
{
protected $table = 'article_categories';
protected $fillable = ['name','hide'];
public function article()
{
return $this->hasMany('App\Article');
}
}
User model
public function article()
{
return $this->hasMany('App\Article');
}
Why am I getting error when trying to get author name and article category name?
Trying to get it in view this way:
$article->user->name
$article->article_category->name
Can't understand the reason :c
Try to change the
return $this->belongsTo('App\User');
and
return $this->belongsTo('App\ArticleCategory');
To
return $this->belongsTo('App\User', 'foreign_key');
and
return $this->belongsTo('App\ArticleCategory', 'foreign_key);
Both will receive the properly foreign key that you provide in yours tables on migrations. Perhaps your foreign keys doesn't recognized.

Fetching Featured Posts with Review and Tag Laravel

I have 4 Eloquent.
class Featured extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
class Course extends \Eloquent {
protected $fillable = array('*');
public function featured() {
return $this->hasMany('Course');
}
public function review() {
return $this->hasMany('Course');
}
public function tag() {
return $this->hasMany('Course');
}
}
class Tag extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
class Review extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
I need to fetch all the featured courses, their review and tags.
Is it possible in 1 query? I have to show some featured posts on front page with their respective reviews and their tags.
This is Laravel 4.
You can use
Course::where('feature',1)->with('review')->with('tags')->get();
feature is a Column which tell course is feature or not.

Laravel 5 hasManyThrough

I have 3 tables: company <-> users <-> invoice.
A company hasMany users.
A user belongsTo a company and, and a user hasMany invoices.
An invoice belongsTo a user.
Now I have an invoice with information about user (customer), and I want to get the user its information about the company so I made an:
An invoice hasManyThrough users, company (so gets the company through user)
Now it doesn't work as it is needed.
Models:
class Company extends Eloquent {
protected $table = 'companies';
public function users()
{
return $this->hasMany('App\User', 'id');
}
public function invoices()
{
return $this->hasManyThrough('App\Company', 'App\User');
}
}
class User extends Model {
protected $table = 'users';
public function usertype()
{
return $this->belongsTo('App\UserType','usertype_id','id');
}
public function company()
{
return $this->belongsTo('App\Company','company_id','id');
}
public function invoice()
{
return $this->hasMany('App\Invoice');
}
}
class Invoice extends Model {
protected $table = 'invoices';
public function users() {
return $this->belongsTo('App\User', 'id');
}
}
Invoice Controller:
class InvoiceController extends Controller {
private $invoice;
public function __construct(Invoice $invoice)
{
$this->invoice = $invoice;
}
public function index(Invoice $invoice)
{
$invoices = $invoice->with('users', 'company')->get();
dd($invoices);
return view('invoice.index', compact('invoices'));
}
public function create()
{
//
}
public function store()
{
}
public function show($id)
{
$invoice = Invoice::with('users')->find($id);
return view('invoice.show', compact('invoice'));
}
public function edit($id)
{
//
}
public function update($id)
{
//
}
public function destroy($id)
{
//
}
}
The dd($invoices) will give a BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::company()
Any further needed information can be provided!
Let's say we have table A and B and C
where table A has many of B (OneToMany) and B has many of C (OneToMany)
inorder to access the table C from table A you can use the Laravel shortcut (HasManyThrough) on the Table A and the problem is solved
BUT If you have table A and B and C
where table A has many of B (OneToMany) and B has many of C (ManyToMany)
you cannot use the laravel's (HasManyThrough) shortcut to access the table C from table A, {because of the pivot table in the middle between B and C} what you can do in this case is very simple:
In this example table A will be [courses], table B will be [chapters], and table C will be [videos]
where every course has may chapters, while a chapter can belong to only one course. in the other hand every chapter has many videos while a video can belong to many chapters.
<?php namespace Moubarmij\Models;
use Eloquent;
class Video extends Eloquent{
protected $table = 'videos';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopePublished($query)
{
return $query->where('published', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
/*************************************************************
* Relations
**************************************************************/
public function chapters()
{
return $this->belongsToMany('Moubarmij\Models\Chapter', 'chapters_videos');
}
}
<?php namespace Moubarmij\Models;
use Eloquent;
class Chapter extends Eloquent{
protected $table = 'chapters';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopePublished($query)
{
return $query->where('published', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
public function scopeWithVideos($query)
{
return $query->with(['videos' => function($q)
{
$q->ordered();
}]);
}
/*************************************************************
* Relations
**************************************************************/
public function course()
{
return $this->belongsTo('Course');
}
public function videos()
{
return $this->belongsToMany('Moubarmij\Models\Video', 'chapters_videos');
}
}
<?php namespace Moubarmij\Models;
use Eloquent;
class Course extends Eloquent{
protected $table = 'courses';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopeVisible($query)
{
return $query->where('visible', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
public function scopeWithChapters($query)
{
return $query->with(['chapters' => function($q)
{
$q->ordered();
}]);
}
public function scopeWithChaptersAndVideos($query)
{
return $query->with(['chapters' => function($q)
{
$q->ordered()->withVideos();
}]);
}
/*************************************************************
* Relations
**************************************************************/
public function chapters()
{
return $this->hasMany('Moubarmij\Models\Chapter');
}
}
You can also do this in the Course class, so when you use ->with('chapters'), it automatically loads the videos too:
public function chapters()
{
return $this->hasMany('Moubarmij\Models\Chapter')->with('videos');
}

Categories