After register redirect to this page.
I want enter this code. (Of course mobile number and the code save in database and send a sms to mobile).
How to enter session code number?
Code
web.php
Route::get('/code', 'HomeController#code')->name('code');
Route::post('/send', 'HomeController#send')->name('send');
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
$user = \App\User::create([
'first_name' => $request->first_name,
.
.
.
.
return redirect()->route('code',['mobile'=>$request->mobile]);
HomeController.php
public function code()
{
return view('Home.send');
}
public function send(Request $request)
{
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
if($user){
$user->verification_code = 1;
$user->save();
alert()->success('ok');
return redirect()->back();
} else {
alert()->error('error');
return redirect()->back();
}
}
send.blad,php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="code">Code</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
I get this error
404
I have verification_code in users table. I want In case of enter true code and mobile number, verification_code change to 1
Take a look on Retrieving Single Models - Not Found Exceptions.
The firstOrFail method will retrieve the first result of the query;
however, if no result is found, a
Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
If the exception is not caught, a 404 HTTP response is automatically sent
back to the user. It is not necessary to write explicit checks to
return 404 responses when using these methods.
So, you can try catch the exeption:
try {
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->firstOrFail();
$user->verification_code = 1;
$user->save();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
return redirect()->back()->with('alert', 'error');
}
return redirect()->back()->with('success', 'ok');
Or otherwise use first instead of firstOrFail, which will return null if there is no record that meets the where conditions:
$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
->whereMobile($mobile)
->first();
if(empty($user)){
return redirect()->back()->with('alert', 'error');
}
$user->verification_code = 1;
$user->save();
return redirect()->back()->with('success', 'ok');
Related
I have this method of trying to get their email to resend verification link if they didnt receive the first time. The problem is i dont want to let them login without verification because this database is connected with a game server and i dont want them to log in without verification. I tried to store the email so the resend button resends it to that email the verification link but after i register and when its trying to redirect me to the verify.blade i get.
Undefinded variable: user
And its pointing to the hidden input which i will show below.
This is my registration function which works fine and registers the user in the database:
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
if(env('CONFIRM_EMAIL') == true){
$this->sendEmail($thisUser);
}
return $user;
}
This is the function that redirects or logins the user depending if i have set to True the email verification:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
if(env('CONFIRM_EMAIL') == false){
$this->guard()->login($user);
}else{
return redirect(route('verifyEmail'));
}
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new Response('', 201)
: redirect($this->redirectPath());
}
and this is the resend function and html code with the hidden input that points the error to the value="$user->email":
protected function resend(Request $request)
{
$user = Account::where('email', $request->email)->first();
if($user){
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return back()->with('user',$user)->with('success', 'A link has been sent to your email');
}
}
<form action=" {!! route('resendEmail') !!}" method="POST">
#csrf
<input type="hidden" name="email" value="{{ $user->email }}">
<button class="btn btn-default db" type="submit" value="Submit">Resend Verification Link</button>
</form>
This is the route for verifyemail which i dont know how to pass the email parameter:
return redirect(route('verifyEmail'));
I am new in Laravel and I am simply create login via jQuery/ajax. According to me its work perfectly code mention below:
Views: login.blade.php
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
email = $("#email").val();
password = $("#password").val();
$.ajax({
type:"POST",
data:{"email":email, "password":password, "_token":"{{csrf_token()}}"},
url:"{{URL::to('login_redirect')}}",
success:function(data){
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$("#success").html('<p style="color:red;">' + data.error + '</p>');
}
}
});
});
});
</script>
<div id="success"></div>
<input type="text" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<input type="submit" name="submit" id="submit" class="btn btn-primary">
contollers: Mycontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Auth;
use Session;
use DB;
class Mycontroller extends Controller
{
public function login_redirect(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
$sql = DB::table('user')->where('email', '=', $email)->where('password', '=', $password)->count();
if($sql > 0)
{
$query = DB::table('user')->where('email', '=', $email)->where('password', '=', $password)->get();
Session::put('user', $query);
if (!isset($_POST))
{
header ("Location: dashboard");
}
else
{
echo json_encode(array('redirect' => "dashboard"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
public function dashboard()
{
$user = Session::get('user');
return view('user.dashboard',['data'=>$user]);
}
public function logout(Request $request) {
Auth::logout();
Session::flush();
return redirect('/login');
}
}
views: dashboard.php
<?php
if(empty($data))
{
header('location:{{url("login")}}');
}
?>
#if (is_array($data) || is_object($data))
#foreach($data as $row)
<h3>Welcome, {{ $row->username }}</h3>
#endforeach
#endif
Logout
Now, the problem is that when I click on logout button it redirect me on login page which is fine but when I directly browse dashboard page on my url without login it again accessible which is wrong. I want once user logout it can't access dashboard directly. So, How can I do this? Please help me.
Thank You
You should need to check the user is login status in the dashboard. For simply, you can try the below answer. As using Laravel, why can't you use the middleware property?
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
public function dashboard()
{
$user = Session::get('user');
if($user)
return view('user.dashboard',['data'=>$user]);
else
return redirect('/login');
}
I'm trying to prevent the user from logging in under some conditions.
My idea is to perform some additional checks after using Laravel's Auth system.
As for the login / register and recover password systems, everything works fine. But I can't seem to be able to log out the user and show a custom error in the login page.
All I want to do is to show a custom "your account was suspended" message under the "email address" field, after verifying if the user was suspended or not.
My code (HomeController), as well as some of my solutions:
public function index(Request $request)
{
// After Laravel logs the user through its authentication system
$user = Auth::user();
if (!isset($user)) {
return redirect('/');
} else {
// we perform some checks of our own
if ($user->suspended != 0) { // suspended by an administrator
$error = trans('errors_login.SUSPENDED_BY_ADMIN');
// return redirect()->route('logout', array('error_msg' => $error));
// return redirect()->route('logout')->withErrors('email','There was an error'); // trying to replace the "email" error
Auth::logout();
$error = ['loginError'=> trans('errors_login.SUSPENDED_BY_ADMIN')];
return view('auth.login', $error);
}
}
...
Just to clarify what the "logout" route is:
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
I'm using Laravel's generated login view:
...
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
Nothing seems to work.
I'm fairly new to Laravel, so I must be missing something.
Thank you.
Laravel's default login controller (App\Http\Controller\Auth\LoginController) uses a trait called AuthenticatesUsers under the hood.
So, whenever a user is authenticated, it calls an authenticated() method prior to sending the login response back, which means, you could probably do something like this.
In App\Http\Controller\Auth\LoginController add a new authenticated() method which overrides AuthenticatesUsers::authenticated().
protected function authenticated(Request $request, $user)
{
if ($user->suspended) {
Auth::logout();
return back()
->with('loginError', trans('errors_login.SUSPENDED_BY_ADMIN'));
}
return redirect()->intended($this->redirectPath());
}
I did it using this also :
protected function sendFailedLoginResponse(Request $request)//this will get triggered if the method above (attemptLogin(Request $request)) returns false.
{
$credentials = [
'email' => $request['email'],
'password' => $request['password'],
];
$valid = Auth::attempt($credentials);
if ($valid == false) { //if user credentials are incorrect
$errors = [$this->username() => trans('auth.failed')];
Auth::logout();
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
} else { // //if user credentials are correct check additional conditions
$user = User::where('email', $request->input('email'))->first();
if ($user->locked == 1) {
$errors = [$this->username() => trans('auth.locked')];
Auth::logout();
throw ValidationException::withMessages([
$this->username() => [trans('auth.locked')],
]);
} else {
$errors = [$this->username() => trans('auth.notactivated')];
Auth::logout();
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
}
}
Not sure if is good enough, but it also working.
I am developing collaborators adding methods to my project management application. this is my collaborators add form.
colllaborators/form.blade.php
<div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
<h4 class="page-header">
Collaborators
</h4>
#if( $collaborators)
#foreach( $collaborators as $collaborator)
<div>
<div>
<span>
<img src="{{ $collaborator->user()->first()->getAvatarUrl() }}" />
</span>
</div>
<button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
data-action="/projects/{{ $project->id }}/collaborators/{{ $collaborator->collaborator_id }}"
routes
Route::post('projects/{projects}/collaborators', [
'uses' => 'Project\Collaborators\Controller#addCollaborator',
'as' => 'projects.collaborators.create',
'middleware' => ['auth']
]);
but when I click to collaborators adding buttons following error messages displayed.
Undefined variable: collaborators (View: C:\Users\Flex\Desktop\ddd\resources\views\collaborators\form.blade.php)
how can I fix this problem
edited
class ProjectCollaboratorsController extends Controller
{
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->back()->with('info', "{$collaborator_username} has been added to your project successfully");
}
private function getId($username)
{
$result = User::where('username', $username)->first();
return (is_null($result)) ? null : $result->id;
}
private function isCollaborator($projectId, $collaboratorId)
{
return Collaboration::where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->first();
}
}
see My other part of the form
<form class="form-vertical" role="form" method="post" action="{{ route('projects.collaborators.create', $project->id) }}">
collaborator form route
Route::get('/collaborators', function(){
return view('collaborators.form');
})->name('collaborators.form');
In your form page, you are checking #if( $collaborators) which checks if the $collaborators variable is not empty and then runs the foreach below it.
After you submit your form, you add the collaborator and redirect back with no collaborators. The if condition then tries to check if the variable is empty. At this point the variable has not been defined and hence it throws that error. To fix this error, return redirect back with the collaborators like this:
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->back()->with(['collaborators'=>$collaborators,'project'=>$project,'info'=> "{$collaborator_username} has been added to your project successfully"]);
}
EDIT:
Using the with method puts the data in the session, i would suggest that you manually redirect to the view and flash the message to that view.
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->route('collaborators.form',['collaborators'=>$collaborators,'project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
Edit 2
I have changed all the return redirect()->back()'s
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
//Get the project too
$project = Project::findOrFail($id);
if( is_null($this->getId($collaborator_username)))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->route('collaborators.form',['project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
And change your routes to
Route::get('/project/{project}/collaborators', function($id){
$collaborators = Collaboration::all();
$project = Project::findOrFail($id);
return view('collaborators.form',compact('collaborators','project'));
})->name('collaborators.form');
I got a problem when trying to redirect back with some results from my sql.
I got a function:
public function postSearch() {
$validator = Validator::make(Input::all(), array(
'search' => 'required'
)
);
if($validator->fails()) {
return Redirect::route('search')
->withErrors($validator)
->withInput();
} else {
$search = Input::get('search');
$user = User::where('username', 'like', '%' . $search . '%')->get();
if($user->count() >= 1) {
return Redirect::route('search')
->with('user', $user)
->withInput();
} else {
return Redirect::route('search')
->with('global', 'Could not find user.')
->withInput();
}
}
return Redirect::route('search')
->with('global', 'Something went wrong, try again later.');
}
but when select was successful in other my file with this code:
#foreach ($user as $users)
<p>
$users->username;
</p>
#endforeach
i got exception undefined user variable. But when i trying to search what doesnt exists in table, 'global' attribute showing my message.
Any ideas why is that not working?
Well, your error is just fine. The $user variable is not defined so you can't iterate over it.
There are 2 things you can do. In your view, you can check if the variable is set
#if (isset($user)
#foreach ($user as $users)
{{ $user->name }}
#endforeach
#endif
You can also set a default value on your code, but you will also need to always your variable to the view. For example:
$user = array();
return Redirect::route('search')
->with('user', $user)
->with('global', 'Could not find user.')
->withInput();
// you will need the $user on your last redirect too
This should fix your problem.