Laravel: Class 'Auth' not found - laravel

I'm making a site with laravel that has a CRUD functie for Users and posts. That part is completed.
After that I made a register function, that also worked.
But when I tried to make a Login page some is wrong.
As soon as I select the, "login"-button a error page shows up with the error:
Class 'Auth' not found
My UserController:
<?php
class UserController extends BaseController {
protected $layout = "layouts.main";
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// get all the users
$users = User::all();
// load the view and pass the users
return View::make('users.index') ->with('users', $users);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
// load the create form (app/views/users/create.blade.php)
return View::make('users.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/create')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = new User;
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully created User!');
return Redirect::to('users');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
// get the User
$user = User::find($id);
// show the view and pass the user to it
return View::make('users.show') ->with('user', $user);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
// get the user
$user = User::find($id);
// show the edit form and pass the User
return View::make('users.edit') -> with('user', $user);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:8'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if($validator->fails()) {
return Redirect::to('users/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
}else{
//store
$user = User::find($id);
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// redirect
Session::flash('message', 'Successfully updated User!');
return Redirect::to('users');
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
// delete
$user = User::find($id);
$user->delete();
// redirect
Session::flash('message', 'Successfully deleted the User!');
return Redirect::to('users');
}
//dit is toegevoegd
public function getRegister() {
$this->layout = View::make('login.register');
}
public function postCreate() {
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->passes()) {
// validation has passed, save user in DB
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::to('login/login')->with('message', 'Thanks for registering!');
} else {
// validation has failed, display error messages
return Redirect::to('login/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
}
}
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getDashboard')));
}
public function getLogin() {
$this->layout = View::make('login.login');
}
public function postSignin() {
$user = array('email'=>Input::get('email'), 'password'=>Input::get('password'));
if (Auth::attempt($user)) {
return Redirect::to('login/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('login/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
public function getDashboard() {
$this->layout = View::make('login.dashboard');
}
}
My Login.blade.php:
#include('header')
<h1>Login page</h1>
{{ Form::open(array('url'=>'login/signin', 'class'=>'form-signin')) }}
<h2 class="form-signin-heading">Please Login</h2>
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password')) }}
<br><br>
{{ Form::submit('Login', array('class'=>'btn btn-large btn-primary btn- block'))}}
{{ Form::close() }}
#include('footer')
And my routes:
<?php
Route::get('home', function()
{
return View::make('home');
});
Route::get('/', function()
{
return View::make('home');
});
Route::resource('users', 'UserController');
Route::resource('posts', 'PostController');
Route::controller('login', 'UserController');
Anybody who can help me?

You need to add use Auth;
or use \Auth::

To use the Auth facade, you have to import it into your namespace.
A better option is to use the helper function instead:
if (auth()->attempt($user)) {
//
}

isset(auth()->user()->id)
to check is user logged in or not.

Related

laravel Resource route shows not found error only for post method

i am working with laravel rest api. i get not found error for only post method in a resource route for UserController.bute all user show in a index method and update user, and show a specific user working good.how can i fixed this problem.
this is route file for UserController
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\User\UserController;
use App\Http\controllers\Buyer\BuyerController;
use App\Http\controllers\Seller\SellerController;
use App\Http\Controllers\Category\CategoryController;
use App\Http\Controllers\Product\ProductController;
use App\Http\Controllers\Transaction\TransactionController;
use App\Http\Controllers\Transaction\TransactionCategoryController;
use App\Http\Controllers\Transaction\TransactionSellerController;
use App\Http\controllers\Buyer\BuyerTransactionController;
use App\Http\Controllers\Buyer\BuyerProductController;
use App\Http\Controllers\Buyer\BuyerSellerController;
use App\Http\controllers\Buyer\BuyerCategoryController;
use App\Http\Controllers\Category\CategoryProductController;
use App\Http\Controllers\Category\CategorySellerController;
use App\Http\Controllers\Category\CategoryTransactionController;
use App\Http\Controllers\Category\CategoryBuyerController;
use App\Http\Controllers\Seller\SellerTransactionController;
use App\Http\Controllers\Seller\SellerCategoryController;
use App\Http\Controllers\Seller\SellerBuyerController;
use App\Http\Controllers\Seller\SellerProductController;
use App\Http\Controllers\Product\ProductTransactionController;
use App\Http\Controllers\Product\ProductBuyerController;
use App\Http\Controllers\Product\ProductCategoryController;
use App\Http\Controllers\Product\ProductBuyerTransactionController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
// return $request->user();
// });
Route::resource('category', CategoryController::class)->except(['create', 'edit']);
Route::resource('products', ProductController::class)->only(['index', 'show']);
Route::resource('sellers', SellerController::class)->only(['index', 'show']);
Route::resource('buyers', BuyerController::class)->only(['index', 'show']);
Route::resource('transactions', TransactionController::class)->only(['index', 'show']);
Route::resource('users', UserController::class)->except(['create', 'edit']);
Route::resource('transactions.category', TransactionCategoryController::class)->only('index');
Route::resource('transactions.sellers', TransactionSellerController::class)->only('index');
Route::resource('buyers.transactions', BuyerTransactionController::class)->only('index');
Route::resource('buyers.products', BuyerProductController::class)->only('index');
Route::resource('buyers.sellers', BuyerSellerController::class)->only('index');
Route::resource('buyers.category', BuyerCategoryController::class)->only('index');
Route::resource('category.products', CategoryProductController::class)->only('index');
Route::resource('category.sellers', CategorySellerController::class)->only('index');
Route::resource('category.transactions', CategoryTransactionController::class)->only('index');
Route::resource('category.buyers', CategoryBuyerController::class)->only('index');
Route::resource('sellers.transactions', SellerTransactionController::class)->only('index');
Route::resource('sellers.category', SellerCategoryController::class)->only('index');
Route::resource('sellers.buyers', SellerBuyerController::class)->only('index');
Route::resource('sellers.products', SellerProductController::class);
Route::resource('products.transactions', ProductTransactionController::class)->only('index');
Route::resource('products.buyers', ProductBuyerController::class)->only('index');
Route::resource('products.category', ProductCategoryController::class)->only(['index', 'update', 'destroy']);
// Route::put('products/{product}/category/{category}', [ProductCategoryController::class, 'update']);
Route::resource('products.buyers.transactions', ProductBuyerTransactionController::class)->only('store');
Route::fallback( function(){
return response()->json([
'message' => 'Page is not found'], 404);
});
Route::get('verify/{token}', [UserController::class, 'verifyEmail'])->name('verify');
And this UserController for store method
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends ApiController
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = User::all();
return $this->showAll($user);
}
/**
* 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',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->password = bcrypt($request->password);
$user->verified = User::UNVERIFIED_USER;
$user->verification_token = User::getVerificationToken();
$user->admin = User::REGULER_USER;
$user->save();
Mail::to($user->email)->send(new VerificationEmail($user));
return $this->showOne($user);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(User $user)
{
//
return $this->showOne($user);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
//enter code here
$request->validate([
'email' => 'email|unique:users,email,'. $user->id,
'password' => 'min:6|confirmed',`enter code here`
'admin' => 'in:'. User::ADMIN_USER . ',' . User::REGULER_USER,
]);
if($request->has('name')){
$user->name = $request->name;
}
if($request->has('email') && $user->email != $request->email) {
$user->verified = User::UNVERIFIED_USER;
$user->verification_token = User::getVerificationToken();
$user->email = $request->email;
}
if($request->has('password')){
$user->password = bcrypt($request->password);
}
if($request->has('admin')) {
if(!$user->isVeified()) {
return $this->errorResponse('only verified user can modified admin rolle', 409);
}
$user->admin = $request->admin;
}
if(!$user->isDirty()) {
return response()->json('You need to specify which feild you want to update', 422);
}
$user->save();
return $this->showOne($user);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
$user->delete();
return $this->showOne($user);
}
// public function verifyEmail(User $user)
// {
// //Mail::to($user->email)
// }
}
Thank you everyone who try to support me.Finally i fixed this issue. This is happend.Beacuse i did not pass Accept: Application/json in postman header.thats why its return 404 not found, not showing the actual $request->validate() error message.
Laravel resource make show method only for get requests
if you need work also post method make another route definition
like
Route::post('users/{user}', [UserController::class, 'show'])->name('users.show');

Variables are not passed in the email template

I'm having this method in my controller
public function update(UserUpdateRequest $request)
{
$request->user()->update([
'name' => $request->username,
]);
Mail::to($request->user())->send(
new UserUpdated( $request->user() )
);
return redirect()->route('account.index');
}
So when the user updates the username an email is send
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('emails.user.updated');
}
And this is the email template
Hi {{ $user->username }},
We would like to inform you that your username has been updated successfully.
If this action wasn't done by you, you need to contact with our support.
But this is throwing an exception in the queues
ErrorException: Undefined variable: user in /storage/framework/views/
Any ideas what I'm doing wrong?
Try passing it to the view via with method and make user variable protected:
protected $user;
public function build()
{
return $this->view('emails.user.updated')->with(['username' => $this->user->username]);
}
And then you can access it like {{ $username }} in your view.
Try this and then access the $user in your view
public function update(UserUpdateRequest $request)
{
$request->user()->update([
'name' => $request->username,
]);
$user = $request->user();
Mail::to($request->user())
->send(new UserUpdated($user));
return redirect()->route('account.index');
}
You can't send $request directly to you email template may this is the reason why you are not able to access the $user

Route [password.update] not defined.Laravel

The user should be able to change his password when he is logged in. But always get i the same error. "Route [password.update] not defined."
I find the route are not in my rout list.
The routes are set in web.php and named in the controller. Where is the mistake?
Routes
//Change Password Routes
Route::get('/setting', 'Auth\UpdatePasswordController#index')->name('password.form');
Route::post('/setting', 'Auth\UpdatePasswordController#updatePassword')->name('password.update');
Controller
class UpdatePasswordController extends Controller
{
/*
* Ensure the user is signed in to access this page
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the form to change the user password.
*/
public function index(){
return view('/setting');
}
/**
* Update the password for the user.
*
* #param Request $request
* #return Response
*/
public function updatePassword(Request $request)
{
$this->validate($request, [
'old' => 'required',
'password' => 'required|min:6|confirmed',
]);
$user = User::find(Auth::id());
$hashedPassword = $user->password;
if (Hash::check($request->old, $hashedPassword)) {
//Change the password
$user->fill([
'password' => Hash::make($request->password)
])->save();
$request->session()->flash('success', 'Your password has been changed.');
return back();
}
$request->session()->flash('failure', 'Your password has not been changed.');
return back();
}
}
view
<form action="{{ route('password.update') }}" method="post" role="form" class="normagin sky-form">
{{csrf_field()}}

Checking if User is activated before sending Password Reset email using Forgot Password

I'm creating a small app using Laravel 5.3. I've applied user activation (via email confirmation) on Laravel's default Auth. But i couldn't find a way to stop sending password reset link if account/user not activated by verifying email address. Currently if a user creates an account and doesn't verify the email address he/she can login using Password Reset link.
this what i've in user table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();;
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('company')->nullable();;
$table->string('password');
$table->boolean('activated')->default(false);
$table->rememberToken();
$table->timestamps();
});
Schema::create('user_activations', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->string('token')->index();
$table->timestamp('created_at');
});
}
UPDATE
I tried to do it by updating the below function. but it's not working
public function reset(Request $request)
{
if (!$request->activated) {
return redirect('/');
} else {
$this->validate($request, $this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
}
I found the solution. Just in case if someone looking for the same solution. Here is the function i overridden
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$user_check = User::where('email', $request->email)->first();
if (!$user_check->activated) {
return back()->with('status', 'Your account is not activated. Please activate it first.');
} else {
$response = $this->broker()->sendResetLink(
$request->only('email')
);
if ($response === Password::RESET_LINK_SENT) {
return back()->with('status', trans($response));
}
return back()->withErrors(
['email' => trans($response)]
);
}
}
Another solution is to overwrite the sendPasswordResetNotification in your User Model:
/**
* OVERWRITE ORIGINAL
* #param string $token
*/
public function sendPasswordResetNotification($token) {
if(!$this->active){
session()->flash('error', 'Your account is disabled.');
return back();
}
$this->notify(new \Illuminate\Auth\Notifications\ResetPassword($token));
}
If the user is not activated, he won't get another email. Instead, he will be returned back to the login page with an error message in the session. To show it you need something like this in your blade file:
#if ($errors->any())
#foreach ($errors->all() as $message)
<div class="alert alert-danger-plain">
<i class="icon-exclamation"></i> {{ $message }}
</div>
#endforeach
#endif
Another straightforward way is to create a new validation rule to check if the user account is activated, And then add the rule to the validateEmail method inside the ForgotPasswordController. Just make sure that you delete the password token everytime you deactivate a user.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\User;
class ActiveUser implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$user = User::whereEmail($value)->first();
if($user) {
if($user->active) {
return true;
}
return false;
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Your account is deactivated.';
}
}
And in the ForgotPasswordController
/**
* Validate the email for the given request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateEmail(Request $request)
{
$this->validate($request, ['email' => [ 'required', 'email', new ActiveUser ]]);
}
And this is how to delete the token at any user deactivation.
$user = \App\user::find(1);
\Illuminate\Support\Facades\Password::broker()->deleteToken($user);

laravel 4 logout after loginning directly?

i try to login by email and password
auth::attempt success login but when redirect to link after login it logout by itself , on localhost all things good but when i upload my project on host this problem occured
login function
public function login(){
$validator=Validator::make(Input::all(),array(
'email' => 'email|required',
'password' => 'required'
));
if($validator->fails()){
$messages = $validator->messages();
$msg='';
foreach ($messages->all() as $message)
{
$msg .= "<li>".$message."</li><br />";
}
return $msg;
}
else{
$email = Input::get('email');
$password = Input::get('password');
$user=Auth::attempt(array(
'email' => $email,
'password' => $password,
'activated' => 1
),true);
//die(Auth::user()->rule);
if($user){
//Auth::login($user);
//die('1111111111');
return 1;
}
else{
return "يوجد خطأ فى البريد الإلكترونى أو كلمة المرور";
}
//die('11111111111111111');
}
}
model
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Mmanos\Social\SocialTrait;
class User extends Eloquent implements UserInterface, RemindableInterface
{
use SocialTrait;
protected $fillable = array('username','password','rule', 'email','active','phone','address','add_info','image','first_name','sec_name','country','area','baqah_id');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public static function is_admin(){
if(Auth::user()->rule=='admin'){
return true;
}
return false;
}
/*
one to one relation
*/
/**
* 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';
}
}
?>

Resources