i have using laravel spatie for permission management: and it is not working with policy, I tried this:
in UserPolicy:
public function view(User $user, User $model)
{
if($user->can('display')) {
return true;
}
}
in controller UserController:
public function index()
{
$this->authorize('view', Auth::user());
$users = User::paginate(10);
return view('users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$permissions = Permission::all();
return view('users.create', compact('permissions'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'min:3'],
'email' => ['email', 'required', 'unique:users'],
'password' => ['required', 'confirmed', 'min:6'],
]);
try {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
$user->syncPermissions($request->permissions, []);
return redirect()->route('users.index')->with('msg', 'user has created successfully');
}catch(\Exception $e) {
return redirect()->back()->with('msg', 'User not registered');
}
}
I have tried index function with user has many permissions including (display) and show me the (Forbbeden page) for all users even with display permission
Related
Each time i register a user, the user automatically gets logged in. How can i disable that, so the user gets returned to the login form after registeration. I came across some articles/answers to similar problems saying the line $this->guard()->login($user); should be removed, but i can't find the line in my code.
#Laravel 8
Below is my Register Controller.
<?php
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::LOGIN;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => ['required', 'string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
I just found the solution to my problem, all i needed was to comment $this->guard()->login($user); in my RegistersUsers file located at vendor\laravel\ui\auth-backend\RegistersUsers.php
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
//$this->guard()->login($user);
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new JsonResponse([], 201)
: redirect($this->redirectPath());
}
in your controller store add this ex.
public function store(Request $request) {
$formFields = $request->validate([
'name' => ['required', 'min:3'],
'email' => ['required', 'email', Rule::unique('users', 'email')],
'password' => 'required|confirmed|min:6'
]);
// Hash Password
$formFields['password'] = bcrypt($formFields['password']);
// Create User
$user = User::create($formFields);
// Login
auth()->login($user);
return redirect('/')->with('message', 'User created and logged in');
}
I have this very strange problem, where when I send an email view in the build method of a mailable, it sends fine, but error's "Trying to get property 'view' of non-object", and thus I can't redirect to a page after sending the mail.
Mailable:
public function __construct($data)
{
$this->email = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$url = URL::temporarySignedRoute(
'verifyCustomer', now()->addMinutes(100),['email'=>$this->email]
);
return $this->from('support#xxxx.com')
->view('validate_email')->with([
'url' => $url,
'email' => $this->email
]);
dd('doesent work here');
}
Register controller:
protected function createCustomer(Request $request)
{
// dd($request->all());
// $this->validator($request->all())->validate();
$validator = Validator::make($request->all(), [
'name' => ['required', 'alpha_dash', 'string', 'max:25', 'unique:customers'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:customers'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
if ($validator->fails())
{
$messages = $validator->messages();
return Redirect::back()->withErrors($validator)->withInput();
foreach($errors->all() as $error) {
echo $error;
}
}
elseif ($validator->passes())
{
$customer = customer::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
'VerifyToken' => Str::random(40),
]);
$customer->SendEmailVerificationNotification();
return redirect()->intended('auth/login');
}
}
SendEmailVerificationNotification:
class SendEmailVerificationNotification
{
/**
* Handle the event.
*
* #param \Illuminate\Auth\Events\Registered $event
* #return void
*/
public function handle(Registered $event)
{
if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
$event->user->sendEmailVerificationNotification();
}
}
}
sendEmailVerification function:
public function sendEmailVerificationNotification()
{
$this->notify(new \App\Notifications\account_verification_notification);
}
account_verification_notification:
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
Mail::to($notifiable['email'])->send(new validate_email($notifiable['email']));
// return (new MailMessage)
// ->line('The introduction to the notification.')
// ->action('Notification Action', url('/'))
// ->line('Thank you for using our application!');
}
Any help would be absolutely fantastic! As this is the third day struggling with this bug :(
Thankyou :)
when i try to register my new members it redirects back to form
i have built a new table for members and class extended authenticatable trait but when i try to register the new member it doesn't register any new member it just redirects back to the same form without any error.
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:member');
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('frontend.auth.member_register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$member = $this->create($request->all());
// dd($request->all());
$this->guard()->login($member);
return redirect($this->redirectPath());
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:members'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(Request $request)
{
return Member::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password'])
]);
}
protected function guard()
{
return Auth::guard('members');
}
It's redirecting because some error exception is being thrown in Handler.php in Exceptions folder by default it redirects to home in handler.php .Use throw($e) in the Handler.php file to check error. You can find error logged also in laravel.log file in the storage folder
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin#gmail.com' for key 'students_email_unique' (SQL: insert into students (name, address, phone, email, faculty, updated_at, created_at) values (Librarian, maitidevi, 9738233231, admin#gmail.com, food, 2019-06-18 09:38:58, 2019-06-18 09:38:58))
Previous exceptions
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required|unique',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}
When I validate with unique this also occurred:
Validation rule unique requires at least 1 parameters.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::latest()->paginate(5);
return view('student.index', compact('students'))
->with('i', (request()->input('page', 1) -1)*5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('student.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Created Successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$student = Student::find($id);
return view('student.detail', compact('student'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view('student.edit', compact('student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'email' => 'required',
'faculty' => 'required'
]);
Student::create($request->all());
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::find($id);
$student->delete();
return redirect()->route('student.index')
->with('success', 'Student deleted successfully');
}
}
I am stuck in my above code? Please help what to do?
In the validation of store method put this instead
'email' => 'required|unique:students,email',
in the Update method, you will need to build the validation rules like this
use Illuminate\Validation\Rule;
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
\Validator::make($request->all(), [
'name' => 'required',
'address' => 'required',
'phone' => 'required',
'faculty' => 'required'
'email' => [
'required',
Rule::unique('students', 'email')->ignore($id),
],
]);
if ($validator->fails()) {
return redirect()
->route('student.create')
->withErrors($validator)
->withInput();
}
$student = Student::findOrFail($id);
foreach ($request->all() as $attribute => $value) {
$student->{$attribute} = $value;
}
$student->save();
return redirect()->route('student.index')
->with('success', 'Student Updated Successfully');
}
I have seen tutorial on how to uses the default authentication mechanism of laravel.
I want to make my authentication to work for different parameters.
I have following to store in the controller which is for registration of an user:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|max:255',
'email' => 'required',
'password' => 'required|alphaNum|min:6',
]);
if ($validator->fails()) {
return redirect('/register')
->withInput()
->withErrors($validator);
}
$confirmation=$this->createConfirmation_code();
$user = new User;
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->username = $request->username;
$user->email = $request->email;
$user->password = -$request->password;
$user->country = $request->country;
$user->street = $request->street;
$user->zip = $request->zip;
$user->state = $request->state;
$user->city = $request->city;
$user->state = $request->city_state;
$user->institute = $request->institute;
$user->confirmation_code=$confirmation;
$user->confirmed='no';
$this->sendEmailReminder($request,$user);
User::create([
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'username' =>$user->username,
'email' =>$user->email,
'password' => bcrypt($user->password),
'country' =>$user->country,
'street' =>$user->street,
'zip' => $user->zip,
'state' =>$user->state,
'institute' =>$user->institute,
'confirmation_code' =>$user->confirmation_code,
'confirmed' => $user->confirmed
]);
return redirect('/confirm')->with('user',$user);
}
Then for login I an using the following:
public function login(Request $request)
{
$rules = array(
'username' => 'required',
'password' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return Redirect::to('/login')
->withErrors($validator);
} else {
$userdata = array(
'username' => $request->username,
'password' => $request->password
);
// attempt to do the login
if (Auth::attempt($userdata)) {
return redirect('/{username}');
} else {
return Redirect::to('/login');
}
}
}
But my login is being failed.
Here is the handle in my Authenticate class:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
}
}
return $next($request);
}
This is my User model:
class User extends Authenticatable
{
protected $fillable = [
'first_name', 'last_name','username','email','password','country','street','zip','state','institute','confirmation_code','confirmed'
];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
}
And I have not made any change to the default auth.php file. Can anyone help me how can i make it work?