Laravel Policy (Too few arguments to function App\Policy) - php

I am trying to setup my policy for users. However I keep on getting an error of:
Too few arguments to function App\Policies\UserPolicy::update(), 1 passed in /vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 481 and exactly 2 expected (View: /resources/views/users/index.blade.php)
ErrorException /app/Policies/UserPolicy.php 20
which is on the UserPolicy#update function
When I am logged in as super_admin, it works fine but it throws this error whenever I am logged in as a user of different role.
Below is my current implementation:
UserPolicy
class UserPolicy
{
use HandlesAuthorization;
public function update(User $user, User $userEdit) {
if ($user->id == $userEdit->id) {
return true;
}
return $user->can('update_user');
}
public function before($user, $ability) {
if ($user->hasRole('super_admin')) {
return true;
}
}
}
UsersController
class UsersController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function edit(User $user) {
$this->authorize('update', $user);
return view('users.edit', [
'user' => User::with('roles', 'level')->find($user->id),
'surveys' => \App\Survey::all(),
]);
}
public function update(UserRequest $request, User $user) {
$this->authorize('update', $user);
$request->save();
session()->flash('success', 'User successfully updated');
// means user is editing his own profile
if (auth()->id() == $user->id) {
return redirect('/dashboard');
} else {
return redirect('/users');
}
}
}
UserRequest
class UserRequest extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
switch ($this->method()) {
case 'POST':
return [
'name' => 'required|string',
'email' => 'required|string|email|max:255|unique:users',
'role' => 'required|exists:roles,id',
'level' => 'required|string',
];
break;
case 'PATCH':
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$this->user->id,
'role' => 'sometimes|exists:roles,id',
'level' => 'sometimes|string',
'password' => 'nullable|sometimes|string|min:6|confirmed'
];
break;
default:
break;
}
}
public function save() {
switch (request()->method()) {
case 'POST':
$this->createUser();
break;
case 'PATCH':
$this->updateUser();
break;
default:
break;
}
}
protected function createUser() {
// random generate password
$password = str_random(8);
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'level_id' => request('level'),
'password' => Hash::make($password),
]);
$user->assignRoleById(request('role'));
Mail::to($user)->send(new WelcomeMail($user, $password));
}
protected function updateUser() {
$user = User::findOrFail($this->user->id);
$user->name = request('name');
$user->email = request('email');
if (request('password') != '') {
$user->password = Hash::make(request('password'));
}
if (request('level') != '') {
$user->level_id = request('level');
}
$user->update();
if (request('role') != '') {
$user->roles()->sync([request('role')]);
}
}
}
AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
\App\User::class => \App\Policies\UserPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
foreach ($this->getPermissions() as $permission) {
Gate::define($permission->name, function($user) use ($permission) {
return $user->hasRole($permission->roles);
});
}
}
protected function getPermissions() {
return Permission::with('roles')->get();
}
}

In my views file I'm calling
#can('update', App\User::class)
<!-- html code --!>
#endcan
instead of
#can('update', $user)
<!-- html code --!>
#endcan
I was not passing the user instance into the function which was causing the error.

In UserRequest you haven't given any parameters when you call $user->update();. The update() function requires for a UserRequest instance, as well as a User.
Give this a try: $user->update(request()->all(), $user)
Edit:
I would just move the following...
$this->authorize('update', $user);
$request->save();
session()->flash('success', 'User successfully updated');
// means user is editing his own profile
if (auth()->id() == $user->id) {
return redirect('/dashboard');
} else {
return redirect('/users');
}
...to the updateUser() function.

Related

How to store bcrypt data using Make request in laravel

This is how I would make such a function
Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
You have two options:
Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.

Multi tenant multi DB can't login to sub domain

I have a multi Tenant / multi DB application & each Tenant has it's own Subdomain with Laravel 7.2
When I go to rootdomain.com/super-admin I can login.
When I go to demo.rootdomain.com/login I can login (default database).
When I go to tenant1.rootdomain.com/login I can NOT login.
I'm using Laravels Auth scaffolding.
I have narrowed it down to the ValidatesRequests trait. If I add the email/password manually I can login to tenant1.rootdomain.com/login
So it looks like this:
public function validate(Request $request, array $rules,
array $messages = [], array $customAttributes = [])
{
return [
"email" => "tenant1#rootdomain.com",
"password" => "#Abc123"
];
return $this->getValidationFactory()->make(
$request->all(), $rules, $messages, $customAttributes
)->validate();
}
Here is my TenantProvider to switch connection for each DB
public function register()
{
if($this->app->runningInConsole()){
return;
}
$host = request()->getHttpHost();
$new_host = explode('.', str_replace('www.', '', $host));
//host must contain at least 3
if(count($new_host) == 3 && $new_host[0] != 'dev'){
config(['database.connections.mysql.database' => 'c4_'.$new_host[0].'_app']);
DB::purge('mysql');
DB::reconnect('mysql');
try {
DB::connection()->getPdo();
if(!DB::connection()->getDatabaseName()){
//reset to default
config(['database.connections.mysql.database' => 'c4_app']);
DB::purge('mysql');
DB::reconnect('mysql');
die("Could not find the database OR Subdomain. Please check your configuration.");
}
} catch (\Exception $e) {
//reset to default
config(['database.connections.mysql.database' => 'c4_app']);
DB::purge('mysql');
DB::reconnect('mysql');
die("Could not open connection to database server. Please check your configuration OR subdomain.");
}
}
// dump('DB Connected...ready to go c4_mvp_app ',DB::connection()->getDatabaseName());
}//end function
And my LoginController
namespace App\Http\Controllers\Auth;
use App\Models\GlobalSetting;
use App\Http\Controllers\Front\FrontBaseController;
use App\Models\Social;
use App\Traits\SocialAuthSettings;
use App\Models\User;
use Carbon\Carbon;
use Froiden\Envato\Traits\AppBoot;
use GuzzleHttp\Client;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Laravel\Socialite\Facades\Socialite;
class LoginController extends FrontBaseController
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers, AppBoot, SocialAuthSettings;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// dd('Base Login', $this->redirectTo);
parent::__construct();
$this->middleware('guest', ['except' => 'logout']);
}
public function showLoginForm()
{
if (!$this->isLegal()) {
// return redirect('verify-purchase');
}
if ($this->setting->front_design == 1 && $this->setting->login_ui == 1) {
return view('saas.login', $this->data);
}
$this->pageTitle = 'Login Page';
return view('auth.login', $this->data);
}
protected function validateLogin(\Illuminate\Http\Request $request)
{
$setting = GlobalSetting::first();
$rules = [
$this->username() => 'required|string',
'password' => 'required|string'
];
// User type from email/username
$user_email = $request->{$this->username()};
$user = User::where('email', $user_email)->first();
if (!is_null($setting->google_recaptcha_key) && (is_null($user) || ($user && !$user->super_admin))) {
$rules['g-recaptcha-response'] = 'required';
}
if (module_enabled('Subdomain')) {
$rules = $this->rulesValidate($user);
}
$this->validate($request, $rules);
}
public function googleRecaptchaMessage()
{
throw ValidationException::withMessages([
'g-recaptcha-response' => [trans('auth.recaptchaFailed')],
]);
}
public function companyInactiveMessage()
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.companyStatusInactive')],
]);
}
public function validateGoogleRecaptcha($googleRecaptchaResponse)
{
$setting = GlobalSetting::first();
$client = new Client();
$response = $client->post(
'https://www.google.com/recaptcha/api/siteverify',
[
'form_params' =>
[
'secret' => $setting->google_recaptcha_secret,
'response' => $googleRecaptchaResponse,
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]
);
$body = json_decode((string) $response->getBody());
return $body->success;
}
public function login(\Illuminate\Http\Request $request)
{
$setting = GlobalSetting::first();
$this->validateLogin($request);
// User type from email/username
$user = User::where($this->username(), $request->{$this->username()})->first();
// dd('LoginController login 140', $user);
if ($user && !$user->super_admin && $user->company->status == 'inactive' && !$user->hasRole('client')) {
return $this->companyInactiveMessage();
}
// Check google recaptcha if setting is enabled
if (!is_null($setting->google_recaptcha_key) && (is_null($user) || ($user && !$user->super_admin))) {
// Checking is google recaptcha is valid
$gRecaptchaResponseInput = 'g-recaptcha-response';
$gRecaptchaResponse = $request->{$gRecaptchaResponseInput};
$validateRecaptcha = $this->validateGoogleRecaptcha($gRecaptchaResponse);
if (!$validateRecaptcha) {
return $this->googleRecaptchaMessage();
}
}
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (
method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)
) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
protected function credentials(\Illuminate\Http\Request $request)
{
//return $request->only($this->username(), 'password');
// dd('credentials 185',$request->{$this->username()});
return [
'email' => $request->{$this->username()},
'password' => $request->password,
'status' => 'active',
'login' => 'enable'
];
}
protected function redirectTo()
{
$user = auth()->user();
if ($user->super_admin == '1') {
return 'super-admin/dashboard';
} elseif ($user->hasRole('admin')) {
$user->company()->update([
'last_login' => Carbon::now()->format('Y-m-d H:i:s')
]);
return 'admin/dashboard';
}
if ($user->hasRole('employee')) {
return 'member/dashboard';
}
if ($user->hasRole('client')) {
return 'client/dashboard';
}
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$user = auth()->user();
$this->guard()->logout();
$request->session()->invalidate();
if (module_enabled('Subdomain')) {
if ($user->super_admin == 1) {
return $this->loggedOut($request) ?: redirect(route('front.super-admin-login'));
}
}
return $this->loggedOut($request) ?: redirect('/login');
}
private function rulesValidate($user)
{
if (Str::contains(url()->previous(), 'super-admin-login')) {
$rules = [
$this->username() => [
'required',
'string',
Rule::exists('users', 'email')->where(function ($query) {
$query->where('super_admin', '1');
})
],
'password' => 'required|string',
];
} else {
$company = getCompanyBySubDomain();
$client = false;
$companies = [];
if ($user && User::isClient($user->id)) {
$client = true;
foreach ($user->client as $item) {
$companies[] = $item->company_id;
}
}
$rules = [
$this->username() => [
'required',
'string',
Rule::exists('users', 'email')->where(function ($query) use ($company, $companies, $client) {
if ($client) {
$query->whereIn('company_id', $companies);
} else {
$query->where('company_id', $company->id);
}
})
],
'password' => 'required|string',
];
}
// dd('rulesValidate 281',$rules);
return $rules;
}
public function redirect($provider)
{
$this->setSocailAuthConfigs();
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider)
{
$this->setSocailAuthConfigs();
$redirectRoute = module_enabled('Subdomain') ? 'front.workspace' : 'login';
try {
if ($provider != 'twitter') {
$data = Socialite::driver($provider)->stateless()->user();
} else {
$data = Socialite::driver($provider)->user();
}
} catch (\Exception $e) {
if ($request->has('error_description') || $request->has('denied')) {
return redirect()->route($redirectRoute)->withErrors([$this->username() => 'The user cancelled ' . $provider . ' login']);
}
throw ValidationException::withMessages([
$this->username() => [$e->getMessage()],
])->status(Response::HTTP_TOO_MANY_REQUESTS);
}
$user = User::where('email', '=', $data->email)->first();
if ($user) {
// User found
\DB::beginTransaction();
Social::updateOrCreate(['user_id' => $user->id], [
'social_id' => $data->id,
'social_service' => $provider,
]);
if ($user->super_admin == 1) {
\Auth::login($user);
return redirect()->intended($this->redirectPath());
}
\DB::commit();
$user->social_token = Str::random(60);
$user->save();
if (module_enabled('Subdomain')) {
return redirect()->to(str_replace(request()->getHost(), $user->company->sub_domain, route('login')) . '?token=' . $user->social_token);
}
\Auth::login($user);
return redirect()->intended($this->redirectPath());
}
if (module_enabled('Subdomain')) {
return redirect()->route($redirectRoute)->withErrors(['sub_domain' => Lang::get('auth.sociaLoginFail')]);
}
throw ValidationException::withMessages([
$this->username() => [Lang::get('auth.sociaLoginFail')],
])->status(Response::HTTP_TOO_MANY_REQUESTS);
}
}
Let me know if you need any other code...thank you!
The code works fine....turns out it was a caching issue.

Laravel : ErrorException (E_ERROR) Call to a member function getAvatar() on null

I already create 3 models objects : User.php, Post.php, DataPribadi.php
This is 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 posts()
{
return $this->hasMany(Post::class);
}
public function datapribadi()
{
return $this->belongsTo(DataPribadi::class);
}
}
This is Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $dates = ['created_at','updated_at'];
public function user()
{
return $this->belongsTo(User::class);
}
}
This is DataPribadi.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DataPribadi extends Model
{
protected $table = 'datapribadi';
protected $fillable = ['namalengkap','namapanggilan','tempatlahir','tgllahir','jeniskelamin','golongandarah','namaayah','namaibu','avatar','user_id'];
public function getAvatar()
{
if(!$this->Avatar){
return asset('images/default.jpg');
}
return asset('images/'.$this->Avatar);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
This is DataPribadiController.php
<?php
namespace App\Http\Controllers;
use App\Exports\DataPribadiExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use App\User;
use PDF;
use App\DataPribadi;
//use App\Http\Requests;
class DataPribadiController extends Controller
{
public function index(Request $request)
{
#ini untuk ambil data yang masuk di variable $request
#dd($request->all());
#untuk search
if($request->has('cari')){
$data_datapribadi = \App\DataPribadi::where('NamaLengkap','LIKE','%'.$request->cari.'%')->get();
}else{
#untuk tampilkan data
$data_datapribadi = \App\DataPribadi::all(); #INI TAMBAHKAN WHERE ISACTIVE = 1
}
return view ('datapribadi.index',['data_datapribadi' => $data_datapribadi]);
}
public function create(Request $request)
{
$this->validate($request,[
'namalengkap' => 'required|min:5',
'namapanggilan' => 'required|min:5',
'email' => 'required|email|unique:users',
'tempatlahir' => 'required',
'tgllahir' => 'required|date_format:Y-m-d',
'golongandarah' => 'required',
'namaayah' => 'required|min:5',
'namaibu' => 'required|min:5',
'avatar' => 'mimes:jpeg,png|dimensions:max_width=400,max_height=400,min_width=100,min_height=100'
]);
#untuk insert user
$user = new \App\User;
$user->role = 'jemaat';
$user->name = $request->namalengkap;
$user->email = $request->email;
$user->password = bcrypt('jemaat');
$user->remember_token = str_random(60);
$user->save();
#untuk insert datapribadi
$request->request->add(['user_id' => $user->id ]);
$datapribadi = \App\DataPribadi::create($request->all());
if($request->hasFile('avatar')){
$request->file('avatar')->move('images',$request->file('avatar')->getClientOriginalName());
$datapribadi->avatar = $request->file('avatar')->getClientOriginalName();
$datapribadi->save();
}
return redirect('/datapribadi')->with('sukses','Data berhasil diinput');
}
public function edit(DataPribadi $datapribadi)
{
#untuk ambil data yang ingin di edit
//$datapribadi = \App\DataPribadi::find($IdPribadi);
return view('datapribadi/edit',['datapribadi'=>$datapribadi]);
}
public function update(Request $request, DataPribadi $datapribadi)
{
$this->validate($request,[
'namalengkap' => 'required|min:5',
'namapanggilan' => 'required|min:5',
'tempatlahir' => 'required',
'tgllahir' => 'required|date_format:Y-m-d',
'golongandarah' => 'required',
'namaayah' => 'required|min:5',
'namaibu' => 'required|min:5',
'avatar' => 'mimes:jpeg,png|dimensions:max_width=400,max_height=400,min_width=100,min_height=100'
]);
//dd($request->all());
#untuk mengupdate data yang ingin di edit
//$datapribadi = \App\DataPribadi::find($id);
$datapribadi->update($request->all());
if($request->hasFile('avatar')){
$request->file('avatar')->move('images',$request->file('avatar')->getClientOriginalName());
$datapribadi->avatar = $request->file('avatar')->getClientOriginalName();
$datapribadi->save();
}
return redirect('/datapribadi')->with('sukses','Data berhasil diupdate');
}
public function delete(DataPribadi $datapribadi)
{
#untuk menghapus data
//$datapribadi = \App\DataPribadi::find($IdPribadi);
$datapribadi->delete($datapribadi);
return redirect('/datapribadi')->with('sukses','Data berhasil dihapus');
}
public function profile(DataPribadi $datapribadi)
{
//$datapribadi = \App\DataPribadi::find($IdPribadi);
$ptingkatpendidikanmaster = \App\TingkatPendidikanMaster::all();
$ppekerjaanmaster = \App\PekerjaanMaster::all();
$phobimaster = \App\HobiMaster::all();
$pperiodekehadiranmaster = \App\PeriodeKehadiranMaster::all();
//dd($tingkatpendidikanmaster);
//Menyiapkan data untuk chart
$categories = [];
$data = [];
foreach($pperiodekehadiranmaster as $pkm){
if($datapribadi->periodekehadiranmaster()->wherePivot('periode_kehadiran_master_id',$pkm->id)->first()){
$categories[]= $pkm->bulantahun;
$data[]= $datapribadi->periodekehadiranmaster()->wherePivot('periode_kehadiran_master_id',$pkm->id)->first()->pivot->jumlah;
}
}
//dd($categories);
//dd($data);
return view('datapribadi.profile',['datapribadi'=>$datapribadi, 'ptingkatpendidikanmaster'=>$ptingkatpendidikanmaster, 'ppekerjaanmaster'=>$ppekerjaanmaster, 'phobimaster'=>$phobimaster, 'pperiodekehadiranmaster'=>$pperiodekehadiranmaster, 'categories' =>$categories, 'data' =>$data]);
}
public function addriwayatpendidikan(Request $request, $iddatapribadi)
{
//dd($request->all());
$datapribadi = \App\DataPribadi::find($iddatapribadi);
if($datapribadi->tingkatpendidikanmaster()->where('tingkat_pendidikan_master_id',$request->tingkatpendidikanmaster)->exists()){
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('error','Data Riwayat Pendidikan Sudah Pernah Didaftarkan');
}
$datapribadi->tingkatpendidikanmaster()->attach($request->tingkatpendidikanmaster,['tahun' => $request->tahun]);
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('sukses','Data Riwayat Pendidikan berhasil dimasukkan');
}
public function addpekerjaan(Request $request, $iddatapribadi)
{
//dd($request->all());
$datapribadi = \App\DataPribadi::find($iddatapribadi);
if($datapribadi->pekerjaanmaster()->where('pekerjaan_master_id',$request->pekerjaanmaster)->exists()){
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('error','Data Pekerjaan Sudah Pernah Didaftarkan');
}
$datapribadi->pekerjaanmaster()->attach($request->pekerjaanmaster,['utamasampingan' => $request->utamasampingan]);
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('sukses','Data Pekerjaan berhasil dimasukkan');
}
public function addhobi(Request $request,$iddatapribadi)
{
//dd($request->all());
$datapribadi = \App\DataPribadi::find($iddatapribadi);
if($datapribadi->hobimaster()->where('hobi_master_id',$request->hobimaster)->exists()){
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('error','Data Hobi Sudah Pernah Didaftarkan');
}
$datapribadi->hobimaster()->attach($request->hobimaster,['intensitas' => $request->intensitas]);
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('sukses','Data Hobi berhasil dimasukkan');
}
public function addperiodekehadiran(Request $request,$iddatapribadi)
{
//dd($request->all());
$datapribadi = \App\DataPribadi::find($iddatapribadi);
if($datapribadi->periodekehadiranmaster()->where('periode_kehadiran_master_id',$request->periodekehadiranmaster)->exists()){
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('error','Data Kehadiran Sudah Pernah Didaftarkan');
}
$datapribadi->periodekehadiranmaster()->attach($request->periodekehadiranmaster,['jumlah' => $request->jumlah]);
return redirect('datapribadi/'.$iddatapribadi.'/profile')->with('sukses','Data Kehadiran berhasil dimasukkan');
}
public function editjumlah(Request $request, $id)
{
return $request->all();
}
public function deletejumlah($iddatapribadi, $idperiodekehadiran)
{
$datapribadi = \App\DataPribadi::find($iddatapribadi);
$datapribadi->periodekehadiranmaster()->detach($idperiodekehadiran);
return redirect()->back()->with('sukses','Data Jumlah Kehadiran Berhasil Dihapus');
}
public function exportExcel()
{
return Excel::download(new DataPribadiExport, 'Datapribadi.xlsx');
}
public function exportPdf()
{
$datapribadi = \App\DataPribadi::all();
$pdf = PDF::loadView('export.datapribadipdf', ['datapribadi' => $datapribadi]);
//$pdf = PDF::loadHTML('<h1>Data Jemaat</h1>');
return $pdf->download('datapribadi.pdf');
}
}
I tried to call it from my singlepost.blade.php using this code :
<img src="{{$post->user->datapribadi->getAvatar()}}" alt="">
and the laravel system error :
ErrorException (E_ERROR)
Call to a member function getAvatar() on null
How can i solve this error??
Thanks in advance..
the problem is in User.php public function datapribadi() { return $this->hasOne(DataPribadi::class); } It should be "hasOne".

Error while getting authenticated user in Laravel using JWT

I was able to login and get user token using JWT in laravel.However, while tring to get authenticated user (getAuthUser) by passing that token, I get following error:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where
clause' (SQL: select * from user where `` = 12 limit 1)"
AuthenticationController:
<?php
namespace Modules\Authentication\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use JWTAuth;
use JWTAuthException;
use Modules\Settings\Entities\Users;
use Modules\Authentication\Http\Requests\Authentication;
class AuthenticationController extends Controller
{
public function __construct()
{
// $this->user = new Users;
$this->guard = \Auth::guard('api');
}
public function login(Authentication $request){
$credentials = $request->only('username', 'password');
try {
// verify the credentials and create a token for the user
$token = JWTAuth::attempt($credentials);
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
public function getAuthUser(Request $request){
$user = JWTAuth::user($request->token);
// dd($user);
return response()->json(['result' => $user]);
}
}
Users Model:
namespace Modules\Settings\Entities;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Users extends Model implements JWTSubject,Authenticatable{
Protected $table="user";
// protected $primaryKey = 'id';
protected $fillable = ['id','username','password','user_status_type_id','client_id','created_userid'];
protected $hidden = [
'password', 'remember_token',
];
public function user_status(){
return $this->belongsTo('Modules\Settings\Entities\UserStatusType','user_status_type_id');
}
public function user_client(){
return $this->belongsTo('Modules\Settings\Entities\Client','client_id');
}
public function role()
{
return $this->belongsToMany('Modules\Settings\Entities\Role','user_role','user_id','role_type_id');
}
public function getAuthPassword() {
return $this->password;
}
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public function getAuthIdentifierName(){}
public function getAuthIdentifier(){}
// public function getAuthPassword(){}
public function getRememberToken(){}
public function setRememberToken($value){}
public function getRememberTokenName(){}
}
Route:
Route::group(['middleware' => 'web', 'prefix' => 'api/v1/authentication', 'namespace' => 'Modules\Authentication\Http\Controllers'], function(){
Route::post('auth/login', 'AuthenticationController#login');
// Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'AuthenticationController#getAuthUser');
// });
});
I am testing it in postman by
GET: ..../api/v1/authentication/user?token={Token}
EDIT:
Now my method for getAuthUser in the controller looks like this:
public function getAuthUser(Request $request){
// $token = JWTAuth::getToken();
// dd($token);
$input = $request->all();
JWTAuth::setToken($input['token']);
// dd($input['token']);
$user = JWTAuth::toUser($input['token']);
// dd($user);
return response()->json(['result' => $user]);
}
and In JWTAuth.php
public function authenticate()
{
// dd($this->getPayload()->get('sub'));
$id = $this->getPayload()->get('sub');
// dd($id);
// dd($this->auth->byId($id));
if (! $this->auth->byId($id)) {
return false;
}
return $this->user();
}
here by doing dd($id), value of id comes but if I try to do dd($this->auth->byId($id)) I get the same error as before.
Try this to retrieve the user instead:
public function getAuthUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(['result' => $user]);
}
Taken from docs, Retreiving the Authenticated user from a token
EDIT:
May not make a difference but just looking at your Model again and I would say that it needs to be
class Users extends Authenticatable implements JWTSubject
rather than
class Users extends Model implements JWTSubject,Authenticatable

Laravel 5 built in User Authentication

I am trying to use Laravel 5 built in User Authentication.In this regard I would like to redirect user to a certain route/page/controller after successfully logged in. I am trying to change code of complied.php file. I am trying to change /home of below code, but it is not working.
trait AuthenticatesAndRegistersUsers
{
protected $auth;
protected $registrar;
public function getRegister()
{
return view('auth.register');
}
public function postRegister(Request $request)
{
$validator = $this->registrar->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException($request, $validator);
}
$this->auth->login($this->registrar->create($request->all()));
return redirect($this->redirectPath());
}
public function getLogin()
{
return view('auth.login');
}
public function postLogin(Request $request)
{
$this->validate($request, array('email' => 'required|email', 'password' => 'required'));
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())->withInput($request->only('email', 'remember'))->withErrors(array('email' => $this->getFailedLoginMessage()));
}
protected function getFailedLoginMessage()
{
return 'These credentials do not match our records.';
}
public function getLogout()
{
$this->auth->logout();
return redirect('/home');
}
public function redirectPath()
{
if (property_exists($this, 'redirectPath'))
{
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
public function loginPath()
{
return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
}
}
Thanks
You are not supposed to change anything in compiled.php
In RedirectIfAuthenticated middleware change,
return new RedirectResponse(url('/home'));
to
return new RedirectResponse(url('/'));
This basically redirects logged in user to desired path, once logged in user returns to website.
so,handle function lookes like below,
public function handle($request, Closure $next) {
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
after that add following in AuthController
public $redirectTo = '/';
public $redirectAfterLogout = '/';
so after successful login user wil be redirected to redirectTo and after logout user will be redirected to redirectAfterLogout.

Categories