How do I read database data from default User class in Laravel? - 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);
}

Related

Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php)

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

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

Why I'm getting a null value when querying a model in eloquent?

I have a problem where I'm getting a null value when querying a model in eloquent, I have a two models User.php and Project.php, When I use tinker and use User.php to check if the data has a relation to Project.php model I got what I want, but when I use the Project.php to check if it has a relation to User.php I'm getting a null value.
This is my code for Project.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public $table = "project";
protected $guarded = [];
public function owner(){
return $this->belongsTo(User::class);
}
}
And this is my code for User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function projects(){
return $this->hasMany(Project::class);
}
/**
* 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',
];
}
This is my result in Tinker:
This is the result when I use tinker and query, as you can see my User.php has a relation to Project.php, But when I use Project.php I'm getting null value.
Have you tried with:
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
Because (quote from the docs):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column.
You should use eager loading to load parent relationship like this :
Project::with('owner')->first()->owner
And confirm that the foreign keys is correct

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

Getting data through pivot table using hasMany relationship

Hello i have these three models:
User.php
<?php namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Kodeine\Acl\Traits\HasRole;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword, HasRole;
/**
* The database table used by the model.
*
* #var stringSS
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function roles()
{
return $this->belongsToMany('App\Models\Role', 'role_user', 'user_id', 'role_id');
}
public function bankBranch()
{
return $this->belongsToMany('App\Models\BankBranch', 'bank_branches_users', 'user_id', 'branch_id');
}
public function permissions()
{
return $this->belongsToMany('App\Models\Permissions', 'permission_user', 'user_id', 'permission_id');
}
}
Bank.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model {
protected $table = 'bank_details';
public function branches()
{
return $this->hasMany('App\Models\BankBranch', 'bank_id');
}
public function users()
{
return $this->hasManyThrough('App\Models\User', 'App\Models\BankBranch');
}
}
BankBranch.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BankBranch extends Model {
protected $table = 'bank_branches';
public function bank()
{
return $this->belongsTo('App\Models\Bank', 'bank_id');
}
public function users()
{
return $this->hasMany('App\Models\User', 'bank_branches_users', 'branch_id', 'user_id');
}
}
Okay now in my application i have the following relationships:
1. User belongs to Many Bank Branches.
2. Bank Branch belongs to one Bank.
3. BankBranch has many users.
Now when a user logs in i want them to only be able to see other users within the same bank branch as the user.
Meaning on my admin->user page i want a list of users in the same branch as the logged in user only.
Unless the logged in user belongs to many other branches, then it should display all the users in the branches the logged in user belongs to.
I am having great difficulty representing this in my eloquent models and fetching the data through my controllers.
to get user bankBranches ids:
$branchIds = Auth::user()->bankBranch()->get()->lists('id');
than gettting all users that belongs to this branches:
$usersInBranches = BankBranch::whereIn('id',$branchedIds)->with('users')->get();
or:
$usersInBranches = User::whereHas('bankBranch', function($query) use ($branchIds) {
$query->whereIn('id',$branchIds);
})->get();
edit or even better:
$usersInBranches = User::whereHas('bankBranch', function($query){
$query->whereIn('id',Auth::user()->bankBranch()->lists('id'));
})->get();

Resources