Laravel post owner relationship - php

i have category_content, contents and users tables which each contents belong to many category_content and category_contentbelong to many contents and each contents belongs to one user and one user has many post on contents table
class Contents extends Model
{
...
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
class ContentCategories extends Model
{
...
public function contents()
{
return $this->belongsToMany(Contents::class);
}
}
class User extends Authenticatable
{
...
public function content()
{
return $this->hasMany(Contents::class);
}
}
by this below code i can find categories content that category id is 7
$nodejsContents = ContentCategories::find('7')->contents;
now, problem is here, how can i get post owner in this query which content is belongs to which user
i tested this code but i get error:
$nodejsContents = ContentCategories::find('7')->contents->user;
Error:
"Undefined property: Illuminate\Database\Eloquent\Builder::$contents"
contents_categories migration:
public function up()
{
Schema::create('contents_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('lang',2)->default('fa');
$table->integer('parent')->default(0);
$table->timestamps();
});
}

user is within contents, so access with closure,
$nodejsContents = ContentCategories::has('contents')->with(['contents' => function($query){
$query->with('user')->get();
}])->find('7');

ContentCategories::find('7')->contents
belongsToMany Contents would return a collection. So you could either loop through the collection to get the related user of Contents
or
ContentCategories::find(7)->contents->with('user');

Related

How to call a relationship who contains another relationship - Laravel

I'm trying to make a site where users have projects, and I'm trying to make a kind of "activity wall" to improve the communication of each project, so this "activity wall" messages belong to the project and the Messages inserted in it belong to the user too. So, I created the migration below:
Schema::create('messages', function (Blueprint $table) {
$table->id();
$table->string('content'); //the message
$table->string('file'); //if has a file
$table->integer('user_id')->constrained(); //to make the relationship with the Users table
$table->integer('projeto_id')->constrained();//to make the relationship with the Projetos (Projectc) table
$table->timestamps();
});
And in Projeto Model, I create the relation.
Projeto.php
public function message()
{
return $this->hasMany(Message::class);
}
The same to
User.php
public function messages()
{
return $this->hasMany(Message::class);
}
And this to
Message.php
public function projetos()
{
return $this->belongsTo(Projeto::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
But the problem is: When I try to get the Messages table with the Project relationship.
public function index($id)
{
$projeto = Projeto::findOrFail($id);
$messages = $projeto->message;
}
I can't get the User relationship to get the owner username of the message to return to my view. What is the better way to do this?
you should use with, to prevent n query:
public function index($id)
{
$projeto = Projeto::with('message', 'message.user') // this will get the relation `message`, and `user` from the message
->findOrFail($id);
$messages = $projeto->message;
}

i want to return the projects of specific user?

I want to return the projects of the authenticated user, but am not getting any. I know the records exist in the database.
This is my model Project:
public function users(){
return $this->hasMany(User::class);
}
this is my model User:
public function projects(){
return $this->hasMany(Projet::class,'user_id');
}
and this is the controller function :
public function projetuser(){
$user = User::find(auth()->user()->id);
return $user->projects;
}
and this my user_projet migration:
public function up()
{
Schema::create('user_projet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('projet_id');
$table->foreign('projet_id')->references('id')->on('projets')->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('membre')->nullbale();
$table->timestamps();
});
}
You are defining a many-to-many relationship incorrectly. Use belongsToMany() instead of hasMany(). Because your pivot table name is not standard (it should be alphabetic order projet_user) you need to include it in the relationship definition as well.
<?php
use Illuminate\Database\Eloquent\Model;
class Projet extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'user_projet');
}
}
class User extends Model
{
public function projets(){
return $this->belongsToMany(Projet::class, 'user_projet');
}
}
Now in your controller you can do this:
public function projetuser(){
return auth()->user->projets;
}
Your question seems to vary between "projet" and "project." I assumed "projet" was the correct spelling, but try to keep this consistent.
Please note also the typo in your migration: nullbale.

Find all posts associated with a tag in laravel

I am building a blog with laravel where a post has many tags. I want to filter all post by a tag. means if I click on "PHP" tag I want to get all associated post.
Here is my code
I have two table first for tags and a second table for the link with posts
tag_table
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tags');
$table->timestamps();
});
}
relation tag table
public function up()
{
Schema::create('article_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
Article Model
class Article extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
tag model
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article');
}
}
Tag Controller
public function show($id,$name)
{
//here I received tag id and name.
$list->with('articles')->get();
return view('articles.tagshow')->withList($list);
}
Eloquent offers the whereHas method that lets you filter on attributes of related models. In order to filter articles by the name of their associated tags, you should do the following:
$articles = Article::whereHas('tags', function($query) use ($tagName) {
$query->whereName($tagName);
})->get();
However, in your case it should be even simpler, because you already have the tag ID in your controller, so you can simply get a tag model by ID and then return related articles:
public function show($id,$name) {
return Tag::findOrFail($id)->articles;
}
Check the docs on querying relations for more details: https://laravel.com/docs/5.6/eloquent-relationships#querying-relations

Laravel user can follow Comment, Category, Post etc

I wanted to implement a follow system where a User can follow Comment, Category, Post and more. I have tried using Laravel Polymorphic relations for this but could not wrap my head around it. If someone can guide me it will be great.
Here is what I have tried.
User Model
public function categories()
{
return $this->morphedByMany(Category::class, 'followable', 'follows')->withTimestamps();
}
Category Model
public function followers()
{
return $this->morphMany(Follow::class, 'followable');
}
Follow Model
public function followable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo(User::class);
}
Follow migration
Schema::create('follows', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->morphs('followable');
$table->timestamps();
});
How can I get the all the categories, comments followed by a user. Also how I can get the Followers of a Cateogry or Commnets etc.
Please help.
You dont't need Follow model.
All you need is pivot table like so
followable
user_id - integer
followable_id - integer
followable_type - string
add folowers method to all your classes which you need to follow
For example
Category Model
public function followers()
{
return $this->morphToMany(User::class, 'followable');
}
Then in User Model
public function followers()
{
return $this->morphToMany(User::class, 'followable');
}
public function followedCategories()
{
return $this->morphedByMany(Category::class, 'followable')->withTimestamps();
}
public function followedComments()
{
return $this->morphedByMany(Comment::class, 'followable')->withTimestamps();
}
public function followedPosts()
{
return $this->morphedByMany(Post::class, 'followable')->withTimestamps();
}
// and etc
public function followedStuff()
{
return $this->followedCategories
->merge($this->followedComments)
->merge($this->followedPosts);
}
Then you can reach your goal by accessing to followers of certain category, comment or post or whatever you wish(if it followable of courcse)
For example:
$folowers = $category->folowers;
// will return all followers this category
$all = $user->followedStuff();
// will return collection of all things followable by the user

Laravel 5.1 Multiple Many to Many Relationship on the Same Model

I seen to of got tangled in Laravel's ORM with the following:
Scenerio: All Users have a Watchlist, the Watchlist contains other Users.
I can't seem the get the relationships to work correctly as they are cyclical, so far I have the following:
class UserWatchlist extends Model
{
protected $table = 'UserWatchlist';
public function Owner() {
return $this->belongsTo('App\User');
}
public function WatchedUsers() {
return $this->hasMany('App\User');
}
}
Schema::create('UserWatchlist', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('Users')->onDelete('cascade');
$table->integer('watched_id')->unsigned();
$table->foreign('watched_id')->references('id')->on('Users')->onDelete('cascade');
$table->timestamps();
});
class User extends Model
{
public function Watchlist() {
return $this->hasOne('App\UserWatchlist');
}
public function WatchedBy() {
return $this->belongsToMany('App\UserWatchlist');
}
}
It is not pulling through the correct in formation i'm expecting. Am I missing something fundamental?
Since UserWatchlist is a pivot table, i suppose you are facing a many to many relationship with both the elements of the relation being the same model (User)
If that is the case, you should not build a model for the pivot table UserWatchlist but all you have to do is to set the relation between the users through the pivot table:
class User extends Model
{
//get all the Users this user is watching
public function Watchlist()
{
return $this->belongsToMany('User', 'UserWatchlist', 'user_id', 'watched_id' );
}
//get all the Users this user is watched by
public function WatchedBy()
{
return $this->belongsToMany('User', 'UserWatchlist', 'watched_id', 'user_id' );
}
}
Check here for more info on many-to-many relationship

Categories