laravel 4 eloquent: one to many result in strange result - laravel

I'm having some really weird issues here with laravel one-to-many relation. I have a one-to-many relation between User and Book. When trying to display the related object from view, the result is either none or the related object depending on how I access it.
User model
//User table: id, username, ...
class User extends ConfideUser implements UserInterface, RemindableInterface {
public function books(){
return $this->hasMany("Book","user");
}
}
Book model
//Book table: id, user, title...
class Book extends Ardent{
public function myUser(){
return $this->belongsTo("User","user"); //I name user_id field as "user"
}
}
view:
#if( ! empty($book->myUser)) //It is always empty
#else
{{$book->myUser}} //It displays the user object
#endif
{{$book->myUser->id}} //ErrorException: Trying to get property of non-object
{{$book->myUser["id"]}} //This works

You didn't tell about ConfideUser class but basically should extend Eloquent
class User extends Eloquent implements UserInterface, RemindableInterface {
public function books(){
return $this->hasMany("Book","user"); // <-- assumed user is custom key
}
}
Same in Book model, ( you didnt tel where Ardent come from and how it's been implemented)
class Book extends Eloquent{
public function user(){
return $this->belongsTo("User", "user");
}
}
You can check relationship and get result using (get users who has book(s))
$books = Book::has('user')->get();
If you query like this
$books = Book::all();
return View::make('books')->with('books', $books);
In your view you can use
#foreach ($books as $book)
{{ $book->user->id }}
#endforeach

Related

Laravel many to many relationship with pivot

I'm using Laravel Filament.
I got a projects and responsibles tables in a many-to-many relationship. But also another table of responsabilityTypes
projects
id
title
responsibles
id
name
responsabilityTypes
id
name
project_responsible
project_id
responsible_id
responsibilityType_id
And here are my relationships setup:
Responsible.php
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType_id')
->withTimestamps()
->using(AcademicoProyecto::class);
}
Project.php
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType_id','sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
I have set up a class for the pivot table like so:
ProjectResponsible.php
use Illuminate\Database\Eloquent\Relations\Pivot;
class AcademicoProyecto extends Pivot
{
}
ResponsibilityType.php
//Don't know how to set up
My question is, when the user is in a Project Edit page and clicks on the "attach" button, in order to add a Responsible record, a Modal pops up to select a Responsible, but I also implemented a Select list to display the different types of responsibilities.
What am I missing to set up in order to access and display the types of responsibilities in the select list and attach it to the pivot table?
Your question asks about "access and display" but you have no controller or view code. But for the model, it's just a simple relationship between two tables, so define it as such:
class AcademicoProyecto extends Pivot
{
use SoftDeletes;
public function responsibilityType() {
return $this->belongsTo(ResponsibilityType::class);
}
}
class ResponsibilityType extends Model
{
protected $fillable = ["name"];
}
Now you simply update the other models to access the relationship in the withPivot() call.
class Responsible extends Model {
public function projects() {
return $this->belongsToMany(Project::class,'rel_project_responsible','responsible_id','project_id')
->withPivot('responsibilityType')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
class Project extends Model {
public function responsibles() {
return $this->belongsToMany(Responsible::class,'rel_project_responsible','project_id','responsible_id')
->withPivot('responsibilityType', 'sort')
->withTimestamps()
->using(AcademicoProyecto::class);
}
}
Now you should be able to do, for example:
$foo = Responsible::with("projects")->first();
foreach ($foo->projects as $project) {
echo $project->pivot->responsibilityType?->name;
}

Laravel eloquent one to many relationship data not showing

i have two tables,
Student table
which have column (id, family_id,name,class,section)
Family table
which have column (family_id, mobile_no, profession)
--
i have created two models.
student model:
class student extends Model
{
}
and
family model
class family extends Model
{
public function student()
{
return $this->hasMany('App\student');
}
}
--
i am able to show all data from student table,
my controller is:
public function index()
{
$finddata = student::orderBy('id', 'asc')->get();
return view('students.index')->with('finddata', $finddata); }
--
what i tried
in family model:
return $this->hasMany('App\students');
what i want;
i want to connect family model with student model..
index page will have all students name only. which i have already done
when i click on student name it should show, all information about particular student, and his family information. right now it's only showing information from student table.
In the student model:
class student extends Model
{
public function family(){
return $this->belongsTo(Family::class,'family_id');
}
}
Then you can access family information in Blade by:
{{$student->family->mobile_no}}
{{$student->family->profession}}
You should better use artisan commands to generate models and controllers, so that you get automatic templates that follow naming conventions, such as uppercase Class names.
You should try this
class student extends Model
{
public function familyId(){
return $this->belongsTo(Family::class,'family_id');
}
}
when you click on student name it will redirect to student/{id}
route
Route::get('student/{id}', 'StudentController#show');
student controller
public function show(Request $request, $id)
{
$student = student::find($id);
return view('student.show')->with('student', $student);
}
student.show.blade file
Mobile no: {{ $student->familyId->mobile_no }}
Profession: {{ $student->familyId->profession }}

Eloquent hasOne relationship Not working laravel 5.4

I am trying to keep a relationship between two tables in my database.
Users Table:
Id User_id Name
Contacts Table:
Id User_Id contacts
I am saving multiple contacts in the contacts table. Now i want to retrieve all the contacts saved to the User_ID. For that, i am trying to establish a hasOne relationship but i get a error for the following code can someone let me know what i am doing wrong? I am following the official documentation for this.
User model:
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasOne('App\contacts','User_Id');
}
}
Contacts Model:
class contacts extends Model
{
public $table = "contacts";
public function Users(){
return $this->belongsTo('App\Users','User_id');
}
}
Controller:
public function eloquentget(){
$contacts = Users::find(1)->contacts->first();
return response()->json($contacts,200);
}
When i try this code in postman i get an Exception :
ErrorException
Trying to get property of non-object
What am i doing wrong? Any help will be appreciated.
Since you are saving multiple Contacts for any given User then you are using the wrong relation. You need to setup a One-Many relationship using hasMany().
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
Try something like this
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
And on your controller, You can use it like this
$contacts= User::find(1)->contacts; // it will return an array of collection
You don't need to use ->first(); because you already used relation hasOne
just use :
$contacts = Users::find(1)->contacts;
return response()->json($contacts,200);

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

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);

Cannot access Collection::$items

I've got some troubles with an eloquent query.
Users have many feeds and feeds have many items.
I need to get all the items that belongs to the feeds of the user order by date.
I've got a pivot table:
feed_user
----------
- id
- feed_id
- user_id
and relationships are defined like this in my models:
class UsersController extends BaseController {
public function feeds() {
return $this->hasMany('feed');
}
class Feed extends \Eloquent {
protected $fillable = [];
public function users() {
return $this->belongsToMany('User');
}
public function items() {
return $this->hasMany('Item');
}
class Item extends \Eloquent {
protected $fillable = [];
public function feed() {
return $this->belongsTo('Feed');
}
But when I do this query...
Auth::user()->feeds->items->orderBy('date', 'DESC')->get();
It returns this error:
Cannot access protected property Illuminate\Database\Eloquent\Collection::$items
There are a couple issues here.
First, the relationship on User model is not correct. A hasMany relationship is one half a one-to-many relationship. This would assume that a feed belongs to one user, and that the feed table has the user_id field. A many-to-many relationship is defined by adding a belongsToMany relationship on both models. So, a user belongsToMany feeds, and a feed belongsToMany users.
class User extends \Eloquent {
public function feeds() {
return $this->belongsToMany('feed');
}
}
Next, the error you're seeing is because Auth::user()->feeds returns a Illuminate\Database\Eloquent\Collection object. You're then trying to access the items attribute on the Collection, which is protected and throws the error you're seeing.
Finally, since Laravel does not use joins for relationships, you cannot order a query by a field on a related table without manually doing the join yourself.
Try using eager loading:
Auth::user()->with('feeds.items')->orderBy('date', 'DESC')->get();

Resources