remember_token missing when add user in laravel 5.2 - php

hello i want to add user when admin log in. i use default Register form.
it success but remember_token is missing and parssword not decrypt.
this is my controller :
public function create()
{
return view('admin/dosen.create');
}
public function store(CreateDosenRequest $request)
{
User::create($request->all());
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
and my request :
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|max:255',
'username'=>'required|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
];
}
Route :
Route::resource('/admin/dosen', 'AdminController',
['except => show, index']);
});

<form method="post" action="#"><input type="hidden" name="_token" value="{{csrf_token()}}"></form>
Just add this in html form.Working :)

Related

Laravel model observer updated & deleted events are not trigerring?

Observer
class FileLogObserver
{
public function updated(FileLogs $fileLogs)
{
$fileChangeLogs = FileChangeLogs::firstWhere('fileId', $fileLogs->filedId);
if ( !empty($fileChangeLogs)) {
$fileChangeLogs->save([
'logDetails' => '1 file updated',
]);
}
}
}
Controller
class FileLogController extends Controller
{
public function update(Request $request,$id){
$validator = Validator::make(
$request->all(),
[
'orderId' => 'required|integer',
'fileId' => 'required|integer',
'status' => 'required|string'
]
);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$data = FileLogs::find($id);
if($data){
$data->orderId=$request->orderId;
$data->fileId=$request->fileId;
$data->status=$request->status;
$data->update();
return response()->json(['status'=>'success','StatusCode'=> 200,'message'=>'Successfully Updated','data'=>$data]);
}
else{
return response()->json(['status'=>'Failed','message'=>'Update Failed'],400);
}
}
}
The created & retrieved methods are being properly triggered. However, the updated & deleted methods not triggered. Gone through many links & read that a reason can be becoz the update is not directly on the model. so, i tried like below in my controller. But update function is not working this method. I'm using Laravel-8 version. Any help is much appreciated.
$data = FileLogs::find($id);
if($data){
$data->update(['$data->orderId'=>'$request->orderId','$data->fileId'=>'$request->fileId','$data->status'=>'$request->status']);
you need to register those observer in App\Providers\EventServiceProvider
like
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
FileLogs::observe(FileLogObserver::class);
}
ref link https://laravel.com/docs/8.x/eloquent#observers

angular post function give me a problem when i want to signup

I want to make a jwt api with laravel and angular , but i have a problem ; when i send my signup data to my laravel server it say's :
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in D:\xampp\htdocs\MySiteBackEnd\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23
and my data is :
{
email : "Artin.zareie#yahoo.com"
family : "aa"
name : "aa"
password : "aaa"
password_confirmation : "aaa"
username : "a"
}
my backend signup function is :
public function signup(SignUpRequest $request)
{
User::create($request);
return $this->login($request);
}
my login code is :
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'ایمیل یا رمزعبور نامعتبر می باشد .'], 401);
}
return $this->respondWithToken($token);
}
and finaly , my SignUpRequest class is this :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SignUpRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'family' => 'required',
'email' => 'required|email|unique:users',
'username' => 'required|unique:users',
'password' => 'required|confirmed',
];
}
}
i'm using angular 6 and laravel 5.7
On your signup method just use
User::create($request->all());
instead of
User::create($request);

How to add user_id to login parameter in Laravel?

Below is some method in a trait AuthenticatesUsers where Illuminate\Foundation\Auth, Laravel.
...
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
...
public function username()
{
return 'email';
}
Originally, my goal is to make another login form with user_id and password in mobile device, so this will check Auth() and if success, it will work some method and automatically logout after then. could you tell me detailed advice?
Additional question.
as Jaskaran Singh's advice I added it also as below.
protected function authenticated(Request $request, $user)
{
if($request->Inn == 'Inn') {
return redirect()->route('mobiles_start', ['Inn' => 'Inn']);
}
elseif($request->Ut == 'Ut') {
return redirect()->route('mobiles_destroy', ['Ut' => 'Ut']);
}
return view('welcome');
}
but if login failed, then it is redirected back to the /login page instead of expected view page that pre defined in the route(mobiles_start and mobiles_destroy) above.
How could I do?
You can login with User ID like this:
if(Auth::loginUsingId($user->id)){
return response()->json(['success' => $user], $this->successStatus);
}
You don't have to extend the core trait or any core Laravel code.
in app/Http/Controllers/Auth/LoginController.php add the following functions, this will override the default functions in AuthenticatesUsers trait.
add username() function
public function username()
{
if(request('id')){
return 'id'; // if request contains id then return it
}
return 'email'; // else return email
}
add validateLogin() function
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required', //remove |string
'password' => 'required|string',
]);
}
that's it.

Custom redirect path if Registration fails on Laravel 5.3

I want to change the redirect path when the Registration fails in Laravel 5.3 right it redirects to the previous page but I want to change it and I can't find out where.
Here is the RegisterController
<?php
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255|min:6',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
?>
And here is the RegistersUsers trait
<?php
use RedirectsUsers;
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
protected function guard()
{
return Auth::guard();
}
protected function registered(Request $request, $user)
{
}
?>
Is there any ideas on how to achieve that, because I want to make a register Modal on the home page, and since it's a modal the user can't see the errors until he opens the registration Modal again, I want to make the **Failed Registration attempts ** always redirects to /register.
Thank you for helping
Override the RedirectsUsers register function in RegisterController as following.
public function register(Request $request) {
$this->validator($request->all())->validate();
$user = $this->create($request->all());
if(empty($user)) { // Failed to register user
redirect('/register'); // Wherever you want to redirect
}
event(new Registered($user));
$this->guard()->login($user);
// Success redirection - which will be attribute `$redirectTo`
redirect($this->redirectPath());
}

extend laravel 5 built-in authentication to login only "if user == active"

I use the included authentication of laravel 5.1.6 and want to know how I can extend it, to work like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
If the user is not "active", the login should not be possible. I have an 'active' column in the users table , with 0 or 1 as value. How can i do this while still using the built in authentication with login throtteling.
edit:
I don't have a postLogin function in the AuthController, only a use AuthenticatesAndRegistersUsers, ThrottlesLogins; , a __construct(), a validator() and a create() function. Do I have to change something in the trait in Illuminate\Foundation\Auth\.. or must I add the the postLogin() function in the AuthController ?
You can just override the getCredentials() method in your AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function getCredentials($request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'active', '1');
}
}
This will add the active = 1 constraint when trying to authenticate a user.
EDIT: If you want a separate error message like BrokenBinary says, then Laravel allows you to define a method called authenticated that is called after a user has been authenticated, but before the redirect, allowing you to do any post-login processing. So you could utilise this by checking if the authenticated user is active, and throw an exception or display an error message if not:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function authenticated(Request $request, User $user)
{
if ($user->active) {
return redirect()->intended($this->redirectPath());
} else {
// Raise exception, or redirect with error saying account is not active
}
}
}
Don’t forget to import the Request class and User model class.
I have now changed the auth middleware /app/Http/Middleware/Authenticate.php (added the block below the comment):
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
#logout if user not active
if($this->auth->check() && $this->auth->user()->active !== 1){
$this->auth->logout();
return redirect('auth/login')->withErrors('sorry, this user account is deactivated');
}
return $next($request);
}
It seems, it also logs out inactive users if they were already logged in.
I would add following first thing in postLogin() function.
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
active is a flag in user table. 0 = Inactive, 1 = active. so whole function would look like following..
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
$credentials = array('email' => $request->email, 'password' => $request->password);
if ($this->auth->attempt($credentials, $request->has('remember'))){
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'Incorrect email address or password',
]);
}
Solved: this link ( tutorial) will help you : https://medium.com/#mshanak/solved-tutorial-laravel-5-3-disable-enable-block-user-login-web-passport-oauth-4bfb74b0c810
step1:
add new field to the User table called ‘status’ (1:enabled, 0:disabed)
step2:
to block the web login , in app/Http/Controllers/Auth/LoginController.php add the follwoing function:
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), ‘password’);
return array_add($credentials, ‘status’, ‘1’);
}
Step3:
to block the user when using passport authentication ( token ) , in the User.php model add the following function :
public function findForPassport($identifier) {
return User::orWhere(‘email’, $identifier)->where(‘status’, 1)->first();
}
Done :)
On Laravel 5.3.* update app/Http/Controllers/Auth/LoginController
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), 'password');
return array_add($credentials, 'active', '1');
}
// your code here

Categories