Laravel relationships not working as expected - laravel

So I have been building this simple Guest book where people leave comments. Ive linked the user model to the comment model and have tried returning the user that posted the comment however I always get an error. Ive made a Ticketing program before this using the same code and it worked and works fine still. See below
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('User::class');
}
}
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
And this is the controller where I am trying to return the results
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$comments = Comment::all();
$user = Auth::user();
$test = User::all();
$average = number_format((Comment::avg('rating')),2, '.', '');
dd($comments->user);
return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);
}
}
Everytime I try and DD the result I get the error
Property [user] does not exist on this collection instance.
I am 100% stumped why this will work on one project and not another. I even rebuilt this little app to see if it was something I had done and I still get the same result.

You're trying to get property of a collection, not an object. So do this:
foreach ($comments as $comment) {
dump($comment->user); // $comment is an object
}

Related

403 user does not have any necessary access rights in laravel usercontroller laratrust

I am trying to get all user in my table but I get an error 403 user does not have the necessary rights. I am using laratrust and vuejs. I have already logged in as a superadministrator. This is my controller class
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('role:user|superadministrator');
}
public function index()
{
return view('user.index');
}
public function getusers(){
$theUser = Auth::user();
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}
}
My api route
Route::get('/allusers','UserController#getusers');
I have tried to go through the documentation but no success.Kindly help me solve this issue
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
use LaratrustUserTrait;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
What about if you try this:
public function getusers(Request $request){
$theUser = $request->user('api');
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}

How to use eloquent on the auth command user in laravel

I am facing a weird error right now
In my controller, when I import the class user like this
use Illuminate\Foundation\Auth\User;
It works when I use eloquent like
public function index()
{
$farms = User::where('role_id', 3)->get();
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
But refuses to work when it comes to table relationships like
public function show($id)
{
$farms = User::with(['animals'])->findOrFail($id);
return view('clinic.show',compact('farms'));
}
showing me this error
"Call to undefined relationship [animals] on model [Illuminate\Foundation\Auth\User]"
But whenever I import the user class as App\User in my controller,
It works in the relationship but refuses to work with the eloquent showing this error
"Call to a member function get() on null"
Now I am kinda confused. Any help will be welcomed
App\User
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}
public function role(){
return $this->belongsTo(Role::class);
}
public function animals(){
return $this->hasMany(Animal::class);
}
public function clinics(){
return $this->hasMany(Clinic::class);
}
public function slaughter(){
return $this->hasMany(Slaughter::class);
}
public function address(){
return $this->belongsTo(Address::class);
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The Illuminate\Foundation\Auth\User class is the parent of the App\User class and animals relation set in the App\Userclass. So you can't call animals relation from Illuminate\Foundation\Auth\User class.
You should remove these functions from the App\User Model:
public static function where(string $string, int $int)
{
}
public static function select(array $array)
{
}

Relationship function is not working in laravel

relationship function is not working of any type. i am creating 2 tables relationship of one to many but it is not working i have no idea at all about that i have follow tutorials and laravel documentation as well but all is vain please guide me thanks.
//this is user model..
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','email','password','image','candidate_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//
}
// and this is candidate model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Candidate extends Model
{
public function user()
{
return $this->hasOne('app\User');
}
}
It shows your model User store candidate_id, so there is 1 Candidate many User..
in Candidate model (Table Name should be candidates)
public function user()
{
return $this->hasMany(User::class);
}
in User model (Table Name should be users)
public function candidate()
{
return $this->belongsTo(Candidate::class);
}
All things were correct, I just call a single attribute of a second table instead of function. In Laravel we call function of related table not its attribute this is the mistake.

Returning null Value for User from Model

I'm getting a null value for the user at http://localhost:8000/messages. I am trying to get the user table values within the Message model. It also gives a null value in the console.
Route
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this-> hasMany(Message::class);
}
}
Snapshot
messages table must have user_id with proper user ID to make belongsTo relationship work.
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

How do I read database data from default User class in Laravel?

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.
routes/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
App/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.
If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.
User Model:
public function post() {
return $this->hasOne('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
then, this gives all user's post along with user name.
$users=User::with('post')->get();
foreach($users as $user)
{
print_r($user->name);
print_r($user->post);
}

Resources