Call to a member function isATeamManager() on a non-object - php

I am getting this error
"Call to a member function isATeamManager() on a non-object".
(RedirectIfNotAManager.php)
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
class RedirectIfNotAManager
{
public function handle($request, Closure $next)
{
if(!$request->user()->isATeamManager())
{
return redirect('articles');
}
return $next($request);
}
}
I have googled it and didn't get any solution,since i am new to laravel kindly help me to solve this problem .its in laravel 5.1 . I have tried other examples and still getting this error..
(This is the User.php Model code:)
<?php
namespace App;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function articles()
{
return $this->hasMany('App\Article');
}
public function isATeamManager()
{
return false;
}
}

That means that your request doesn't have a user stored on it. So no one is logged in or your session isn't working correctly. $request->user() is a function that runs to try to pull the current user, by default if someone is logged in it will return a user object or a null value I believe. So most likely you are getting a null value back. You could change your if statement to this:
if(!$request->user() || !$request->user()->isATeamManager()) {

i got the solution..
This is working!!
public function handle($request, Closure $next)
{
if ($request->user()) { // This will return null if the user is not logged in, which evaluates to false
if (!$request->user()->isATeamManager()) {
return redirect('articles');
}
}
return $next($request);
}
}

Related

How to obtain three level model data laravel

Updated
User model
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens, HasRoles;
const MALE = 'male';
const FEMALE = 'female';
protected $guard_name = 'sanctum';
public function educationalBackgrounds()
{
return $this->hasMany("App\Models\Users\EducationalBackground", "user_id");
}
public function seminars()
{
return $this->hasMany("App\Models\Users\Seminar", "user_id");
}
}
I have child table EducationalBackground which is related to User table
class EducationalBackground extends Model
{
use HasFactory;
protected $table = 'users.educational_backgrounds';
protected $fillable = [
'user_id',
'studies_type',
'year',
'course',
];
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function educationalAwards()
{
return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id");
}
}
And a third table that i want to access the award field
class EducationalAward extends Model
{
use HasFactory;
protected $table = 'users.educational_awards';
protected $fillable = [
'educational_background_id',
'award',
'photo',
];
public function educationalBackground()
{
return $this->belongsTo('App\Models\Users\EducationalBackground', 'educational_background_id');
}
}
I have api get route here
Route::get('/educational-background/{id}', [UserProfileController::class, 'getEducationalBackground']);
Here is my api method it works fine. But i want to go deeper and access the data of third table.
public function getEducationalBackground($id)
{
$educationalBackground = EducationalBackground::with('user')->where('user_id', $id)->get();
return response()->json($educationalBackground, 200);
}
It looks like you're not really grasping the concept of relations yet. Also, I'd advise you to look into route model binding :) What you basically want to be doing is:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds()->with('educationalAwards')->get();
}
Also, when you're pretty sure that whenever you want to use backgrounds, you also want to use the awards, you can add the with(...) to the model definition like so:
class EducationalBackground extends Model
{
...
protected $with = ['educationalAwards'];
}
That way, you can simplify your controller method to:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds;
}

how to pass parameters to relationship .parameter passed to relationship from controller to model in laravel.but now working

in my controller parameter passed to posts function in user model with construct method .
i want the users that have posts and posts should be according to the parameter.
class MyController extends Controller
{
private $user;
public function __construct(User $getuser)
{
$this->user = $getuser;
}
public function index($id = 2)
{
$posts = $this->user->posts($id);
$user = User::whereHas('posts')->find($id);
return $user;
}
}
in my user model parameter accessed and passed to relationship .
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
function posts($id)
{
return $this->hasMany('App\Post')->where('id',$id);
}
}
it works when use like this
"return $this->hasMany('App\Post')->where('id',1);"
but not working with passed parameter. getting this error
"Symfony\Component\Debug\Exception\FatalThrowableError Too few
arguments to function App\User::posts(), 0 passed in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
on line 415 and exactly 1 expected"
You're making life difficult for yourself and not allowing the framework to do the heavy lifting.
web.php
Define a route that accepts a User identifier
Route::get('/users/{user}', 'UserController#show');
User.php
public function posts() {
return $this->hasMany(App\Post::class);
}
UserController.php
public function show(User $user) {
return view('users.view', compact('user');
}
resources/views/users/view.blade.php
ddd($user->posts);

Problem with Laravel Eloquent - relation not working

I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}

laravel- Error- Data missing

I'm trying to code from .\app\Http\Controllers\DienController.php
public function store(Request $request)
{
try
{
$dien=new Dien();
$phong=Phong::find($request->p_id);
$thang=date("m",strtotime($request->d_taoMoi));
$nam=date("Y",strtotime($request->d_taoMoi));
$dien->d_ma=$thang.$nam.($phong->p_ma);
$dien->p_id=$request->p_id;
$dien->d_chisoDau=$request->d_chisoDau;
$dien->d_chisoCuoi=$request->d_chisoCuoi;
$dien->d_slhienTai=$phong->p_soNguoi;
$dien->dg_id=$request->dg_id;
$id=Dongia::ALL()->max('dg_id'); //Lấy đơn giá id vừa cập nhật mới nhất
$dongia=Dongia::find($id);
$dien->d_tiendienPhong=($request->d_chisoCuoi-$request->d_chisoDau)*($dongia->dg_tienDien);
$dien->d_tiendienSV=($request->d_chisoCuoi-$request->d_chisoDau)*($dongia->dg_tienDien)/($phong->p_soNguoi);
$dien->d_taoMoi=$request->d_taoMoi;
$dien->save();
// $nuoc=new Nuoc();
return redirect(route('dien.index'));
}
catch(QueryException $ex)
{
return response(['error'=> true ,'message'=> $ex->getMessage()],500);
}
//
}
My Model (App\Dien.php) is:
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Phong;
use App\Nuoc;
class Dien extends Model
{
const CREATE_AT='d_taoMoi';
const UPDATE_AT='d_capNhat';
//
protected $table='dien';
protected $fillable=['d_ma','d_chisoDau','d_chisoCuoi','d_tiendienPhong','d_tiendienSV','d_slhienTai','dg_id','p_id'];
protected $guarded=['d_id'];
protected $primaryKey='d_id';
protected $dates=['d_taoMoi','d_capNhat'];
protected $dateFormat='Y-m-d H:i:s';
public function dongia()
{
return $this->belongsTo('App\Dongia','dg_id','dg_id');
}
public function Phong()
{
return $this->belongsTo('App\Phong','p_id','p_id');
}
//
}
But when i ran that program,i had an issue with that."Data missing". I wonder how i use wrong from variable with "$thang".
InvalidArgumentException
Data missing
Please give me an advice, thank you very much.
Use this code on model and you will get your data without error of data missing if created_at and updated_at is null
public $timestamps = false;

How do I call model function on create event? Laravel-5

I'm trying to create a referral url when a user is first created.
My function inside my User model looks like this:
private function make_url()
{
$url = str_random(40);
$this->referral_url->url = $url;
if ($this->save()){
return true;
}
else{
return false;
}
}
Within the model, I've tried doing this but didn't work
USER::creating(function ($this){
$this->make_url();
})
I also tried calling it in my User Controller within the create user action
public function create(UserRequest $request)
{
$data = $request->all()
$data['password']= bcrypt($request->input('password'));
if($user=User::create($data))
{
$user->make_url();
}
}
I get this error in return
Indirect modification of overloaded property App\User::$referral_url has no effect
Thanks in advance for your help guys =]
p.s: If there's a better way to go about creating referral urls please tell me.
update
My entire user model
<?php
namespace App;
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;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = [
'first_name',
'last_name',
'url',
'email',
'password',
'answer_1',
'answer_2',
'answer_3'
];
protected $hidden = ['password', 'remember_token'];
public function make_url()
{
$url = str_random(40);
$this->referral_url->url = $url;
if ($this->save()){
return true;
}
else{
return false;
}
}
public function user_info()
{
return $this->hasOne('App\UserInfo');
}
public function sec_questions()
{
return $this->hasOne('App\SecurityQuestions');
}
public function referral_url()
{
return $this->hasOne('App\ReferralUrl');
}
}
update
I modified the function in the model to look like this now.
public function make_url()
{
$url = str_random(40);
$referral_url = $this->referral_url;
$referral_url = new ReferralUrl();
$referral_url->user_id = $this->id;
$referral_url->url = $url;
if ($referral_url->save()){
return true;
}
else{
return false;
}
}
When I call
$user->make_url()
I'm able to create it and it shows up in my db, but I also get the error-
Trying to get property of non-object
Normally the creating method should be called within boot():
public static function boot() {
parent::boot();
static::creating(function ($model) {
$model->foo = 'bar';
});
}
This would then be called automatically before the model is saved for the first time.
The problem that I see with your code is that you're attempting to modify a relation which doesn't exist yet.
So to explain, the hasOne method will attempt to join the current model to the remote model (in your case a ReferralUrl model) in SQL, but it can't do that before you save your model because your model doesn't exist in the database.
With your second attempt, the ReferralUrl object is the one that is changing, so that is the one that you need to save:
public function make_url() {
$url = str_random(40);
$referral_url = $this->referral_url
$referral_url->url = $url;
if ($referral_url->save()){
return true;
} else {
return false;
}
}

Categories