Access user's properties (with pivot table) laravel 5.1 - laravel

I have a users table. The user has possibility to upload a post. The post is saved well to the database. The users can follow each other - so on a pivot table each follower_id has followees_id.
I need to get the posts of the current user followee's . I am kinda messed with getting it from a pivot table.
Here's my code so far:
controller:
protected function get_followee_posts($followee_posts) ////$followee_posts passed from the route.
{
$user = $this->user;
$user->followee()->attach($followee_posts);
$followee_posts = User::find($followee_posts);
}
view:
<div class="following_posts">
<p> Posts from people you're following: <p>
#foreach ($user->follower_id->followee_id->posts as $post)
<form action="/html/tags/html_form_tag_action.cfm" method="post">
<textarea name="comments" id="comments" style="width:96%;height:90px;background-color:white;color:black;border:none;padding:2%;font:22px/30px sans-serif;">
{!! $posts->full_post !!} </textarea>
</form>
#endforeach
route:
Route::get('hub/{followee_posts}','HubController#get_followee_posts')->name('followee_posts');
I am getting an error with the current code saying:
ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105:
Trying to get property of non-object
Any help would be lovely. Thank you.

Your not too specific about your schema, but this is how I would go about it.
User Model
class User extends Model
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
}
Follower Model
class Follower extends Model
{
protected $table = 'followers';
public function user()
{
return $this->belongs_to('User');
}
public function posts()
{
return $this->hasMany('Post', 'user_id', 'follower_id');
}
}
Post Model
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongs_to('User');
}
}
The followers table would look something like this:
user_id
follower_id
You could then use eloquent method chains to get the posts of a users followers:
// Get Users object with followers and followers posts
// We use with() to eager load relationships
$user = User::with('followers.posts')->find(2);
// Return associative array of post objects
$postsArray = $user->followers->lists('posts');
// Combine posts into a single collection
$posts = (new \Illuminate\Support\Collection($postsArray))->collapse()->toArray();
print_r($posts);

Related

Trying to get property 'first_name' of non-object

I am trying to fetch digitizing order related to the user but unfortunately, I am facing an error.
Please see this error: https://flareapp.io/share/VmeWJ47Q
Controller
public function index()
{
$data=
[
'digitizings'=>Digitizing::with('user')->paginate(8)
];
return view('front_end.profile.digitizing.digitizing_view_order',$data);
}
User Model
class User extends Authenticatable
{
use Notifiable;
public function digitizing()
{
return $this->hasMany('App\Digitizing','user_id');
}
}
Digitizing Model
class Digitizing extends Model
{
protected $fillable = ['id','order_name','height','width','urgent','image',
'order_placement','required_format','order_fabric','instruction','user_id'];
protected $table ="digitizing_orders";
public function user()
{
return $this->belongsTo('App\User');
}
}
HTML view
#foreach($digitizings as $key =>$digitizing)
<tr>
<td>DPO# {{$digitizing->id}}</td>
<td>{{$digitizing->created_at}}</td>
<td>{{$digitizing->order_name}}</td>
<td>{{$digitizing->user->first_name}}</td>
<td>{{$digitizing->user->email}}</td>
<td>{{$digitizing->released_date ?? 'processing'}}</td>
<td>View
</td>
</tr>
#endforeach
Does every Digitizing-Entry has set a valid user_id in database? Try checking eager loaded data is set before accessing it.
Try to send the data to the view like this:
public function index()
{
$digitizings = Digitizing::with('user')->paginate(8);
return view('front_end.profile.digitizing.digitizing_view_order',$digitizings);
}

one to may relationship, Display all post along with there users

//Post table
user()
`belongsTo(User::class);`
//user table
posts()
hasMany(post::class);
//I want to get all the post available in the DB, Display along with the users associated with the post.
Use foreign key and primary key in relationships to get the results.
In Post
public function user()
{
return $this->belongsTo('App\User','users_id','users_id') //first parameter-foreign key,second parameter-local key
}
In User
public function posts()
{
return $this->hasMany('App\Post','users_id','users_id')
}
Now get all the posts using
$posts = Post::get();
return view('your-view')->with('posts',$posts);
You can retrieve user information in view using
#foreach($posts as $post)
$user = $post->user->name;
#endforeach
Hope it helps..
Guessing your relations look like this:
User:
public function posts()
{
return $this->hasMany('App\Post');
}
Post:
public function user()
{
return $this->belongsTo('App\User')
}
You could get all the posts in your controller, like this:
$posts = Post::get();
return view('your view', $posts);
And in your blade, to display posts and their users, do it like this:
#foreach($posts as $post)
$post->user->name
#endforeach
$posts = Post::with('user')->get();

Laravel One To Many Relationship

I have an Author model and Blog model.
I also set up a table with the author_id and blog_id. The table is called "author_blog".
Below is how I am defining my relationships:
Author Model:
public function blogs()
{
return $this->hasMany('App\Blog', 'author_id');
}
Blog Model:
public function author()
{
return $this->belongsTo('App\Author', 'blog_id');
}
In my view I am trying to do $blog->author->first_name. The first name is a column on the Authors table.
I keep getting
trying to get property on non-object.
Any ideas?
UPDATE:
I have removed the intermediate table and instead put an "author_id" on my blogs table and shortened it as such.
Author Model:
public function blogs()
{
return $this->hasMany('App\Blog');
}
Blog Model:
public function author()
{
return $this->belongsTo('App\Author');
}
In my BlogController, when I define the view, I grab a collection of blogs via $blogs = Blog::all();
In my view I just loop through the blogs to show each individually like...
#foreach ($blogs as $blog)
<div>{{ $blog->author->first_name }}</div>
#endforeach
For one to many relationship you don't need another table to handle your foreign key.
Just add author_id foreign key with your blogs table. then define your relations
like below,
Author Model:
public function blogs()
{
return $this->hasMany('App\Blog', 'author_id');
}
Blog Model:
public function author()
{
return $this->belongsTo('App\Author', 'author_id');
}
view:
before that make sure your query return a valid collection.
#foreach ($blogs as $blog)
<div>#if( $blog->author) {{ $blog->author->first_name }} #endif </div>
#endforeach
For further more details : https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
with belongsToMany relation you can define your middle table(author_blog)
In Author model:
public function blogs()
{
return $this->belongsToMany(Blog::class,'author_blog','author_id','blog_id');
}
author_blog => middle table
author_id => foreignPivotKey
blog_id => relatedPivotKey

Access followers data Laravel 5.8 and Eloquent

I have a base table setup for followers and the Follower model has the relationship belongsTo with User model. User model has the relationship belongsToMany with the Follower model. The followers table has "id, follower_id, leader_id"
I'm trying to access the followers table through the User model but it won't let me do it. I must be doing something wrong, but I have worked with Eloquent relationships before and I have always had it working then. Can someone take a look at the code snippets below and point out what is wrong?
User Model
public function followers(){
return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}
public function followings(){
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
Follower model
protected $table = 'followers';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
$this->belongsTo('App\User');
}
FollowerController
Old controller for old relationship
// public function followUser($id){
// $user = User::find($id);
// if(!$user){
// return redirect()->back()->with('error', 'User does not exist.');
// }
// $user->followers()->attach(auth()->user()->id);
// return redirect()->back()->with('success', 'You now follow the user!');
// }
//New controller
public function followUser($id){
$user = User::find($id);
if(!$user){
return redirect()->back()->with('error', 'User does not exist.');
}
$follow = new Follower;
$follow->follower_id = Auth::user()->id;
$follow->leader_id = $user;
$follow->save();
return redirect()->back()->with('success', 'You now follow the user!');
}
UserController
// This is a test function
public function index($id){
$userid = Auth::user();
$user = User::find($id)->followers;
$recipe = Recipe::find(5);
$savedRecipes = Save::where('user_id', '=', $userid);
return view('welcome')->with('recipe', $recipe)->with('user', $user)->with('savedRecipes', $savedRecipes);
}
Test View
<div class="content">
<div class="title m-b-md">
Welcome to the TestLab: {{$user->followers->follower_id}}
<br>
This throws an error of "Property not found on this instance".
All the namespacing is all in order so that is not the issue either.
What is the problem here?
If you have a One To Many relationship between users and followers you defined your relationship wrong, if a follower belongs to a User, a User hasMany followers:
public function followers(){
return $this->hasMany('App\Follower','user_id');
}
Take a look at the docs
Your controller:
public function index($id){
$user = User::find($id);
return view('welcome')->with('user', $user);
}
You could access each follower from a user using a foreach loop:
#foreach($user->followers as $follower)
{{$follower->anyAttributeFromTheFollower}}
#endforeach

Laravel Category Model Relationships

I have the following table structure in my database.
Table Name: tiles
Columns: id, tile_name, tile_thumb, tile_snippet
Table Name: tags
Columns: id, tag_title
Table Name: tile_tags
Columns: id, tile_id, tag_id
Models:
Tile, Tag, TileTag
In my main model class for entries I am specifying the following relationship to a model called TileTag which is a pivot table.
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsTo('Tiles\TileTag');
}
}
During my foreach loop it returns the tile_name and any other columns from my table, except the ones joined by the relatipnship.
#foreach($tiles as $tile)
<a href="tile/{{$tile->tile_name}}">
<li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
{!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
</li>
</a>
#endforeach
How can I get my categories/tags linked to my primary entries when they are sorted during each loop?
I try returning the data during the loop by {{ $tile->tags->tag_title }} but it returns an empty string.
Controller Method:
class TileController extends Controller {
/**
* Display a listing of tiles from the database.
*
* #return Response
*/
public function index() {
// Get tile data from the model
$tiles = \Tiles\Tile::all();
return view('pages.index', compact('tiles'));
}
Returned Array:
I think that you don't have to create a model for Tile_Tag. Laravel can handle ManyToMany relationships out of the box (I suppose that this is the type of the relationship because you use pivot table). Your models should be
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsToMany('Tiles\Tag');
}
}
and
class Tag extends Model {
protected $table = 'tags';
public function tiles() {
return $this->belongsToMany('Tiles\Tile');
}
}
Laravel will know that you have a pivot table named "tag_tile" with columns "tag_id" and "tile_id". Check the relevant documentation here
Then you can iterate through tags collection for each tile like this
#foreach ($tiles as $tile)
{!!$tile->tile_name!!}
#foreach ($tile->tag as $tag)
{!!$tag->tag_title!!}
#endforeach
#endforeach
Hope it helps.

Resources