Laravel/Vue form Validation - laravel

I'm having a problem with validation when it comes to Laravel and Vue
My controller has logic like this.
$this->validate($request, [
"name" => ["required", "min:3"]
]);
Vue only recognizes one of the two validations, however. For example, if the text field isn't at least 3 characters long Vue will still allow all to go through, claiming that the name field is still required.
The only error that displays on the front end is the "required" rule, there's nothing there for "min:3".
Any advice? Or if anyone can lead me to a good source with VueJS/Laravel validation that would be awesome too,
thanks in advance.
Another odd thing is that though the name field is required even if it is fulled in, Laravel still returns that error in the console 422.
VueJS Component
<template>
<!-- Third paramater in v-bind="" class will be used in either -->
<div>
<form v-on:submit.prevent>
<div class="section">
<div class="field level">
<p class="control has-text-centered">
<input
id="name"
name="name"
v-model="item.name"
class="input is-rounded is-large"
type="text"
placeholder="Enter Todo.."
v-bind:class="[
item.name ? 'is-success' : 'is-normal',
'plus'
]"
/>
</p>
</div>
<div class="alert alert-danger" v-if="errors && errors.name">
{{ errors.name[0] }}
</div>
<button
#click="addItem()"
class="button is-primary is-fullwidth"
>
<font-awesome-icon
icon="plus-square"
class="color is-primary"
/>
</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function() {
return {
item: {
name: ""
},
errors: {}
};
},
methods: {
addItem() {
// if (this.item.name === "") {
// return;
// }
axios
.post("api/item/store", {
item: this.item
})
.then(response => {
if (response.status == 201) {
this.item.name = "";
this.$emit("reloadlist");
this.errors = {};
}
})
.catch(error => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
console.log(error);
});
}
}
};
</script>
<style scoped>
p {
margin: auto;
}
</style>
PHP Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Item;
use Illuminate\Support\Carbon;
class ItemsController extends Controller
{
/**
* Display a listing of the item resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Item::orderBy("created_at", "DESC")->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
"name" => ["required", "min:3"]
]);
$newItem = new Item;
$newItem->name = $request->item["name"];
$newItem->save();
dd("Hello, World");
return $newItem;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$existingItem = Item::find($id);
if ($existingItem) {
$existingItem->completed = $request->item["completed"] ? true : false;
$existingItem->completed_at = $request->item["completed"] ? Carbon::now() : null;
$existingItem->save();
return $existingItem;
}
return "Item not found.";
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$existingItem = Item::find($id);
if ($existingItem) {
$existingItem->delete();
return "Item '{$existingItem->name}' deleted successfully.";
}
return "Item not found.";
}
}

Item is already an object so you dont need it to put in an object variable and the name it item.
Change your axios request to:
methods: {
addItem() {
// if (this.item.name === "") {
// return;
// }
axios
.post("api/item/store", this.item)
.then(response => {
if (response.status == 201) {
this.item.name = "";
this.$emit("reloadlist");
this.errors = {};
}
})
.catch(error => {
if (error.response.status == 422) {
this.errors = error.response.data.errors;
}
console.log(error);
});
}
}
I think this will solve your problem.

Related

Return result according to authenticated user in laravel

I have a list of users where there are four different user types('SA','Admin','User','Candidate') and I am displaying them using yajrah datatable and what i am trying to do is that when the SA is logged in then the list should have only Admin,User and Candidate.
Similarly when Admin logins then the list should return only Candidate and Users.
My Front-end:
Front-End
I don't know how to pass query for that
my Users datatable
class UsersDataTable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
return datatables()
->eloquent($query)
->addColumn('action', function($data){
$button = '<a href="'.route('user.edit',$data->id).'"><button type="submit" name="edit" id="'.$data->id.'"
class="edit btn btn-primary btn-sm">Edit</button></a>';
$button .= '<a><form action="user/'.$data->id.'
" method="post">
'.csrf_field().'
'.method_field('DELETE').'
<button type="submit" name="delete" id="'.$data->id.'"
class="delete btn btn-danger btn-sm">Delete</button></form></a>';
return $button;
});
}
/**
* Get query source of dataTable.
*
* #param \App\User $user
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(User $user)
{
return $user->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->setTableId('user')
->columns($this->getColumns())
->minifiedAjax()
->dom('frltip');
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('id'),
Column::make('name'),
Column::make('email'),
Column::make('usertype'),
Column::make('created_at'),
Column::make('action'),
];
}
My controller :
/**
* Display a list of the users
*
* #param \App\DataTable\UsersDataTable $dataTable
* #return \Illuminate\View\View
*/
public function index(UsersDataTable $dataTable)
{
return $dataTable->render('users.index');
}
my migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->softemail();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->enum('usertype', ['super admin','admin', 'user','candidate']);
$table->rememberToken();
$table->timestamps();
});
}
Any help will be appreciated.
Datatable
<?php
namespace App\DataTables;
use App\User;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class UsersDataTable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
return datatables()
->eloquent($query)
->addColumn('action', function($data){
$button = '<a href="'.route('user.edit',$data->id).'"><button type="submit" name="edit" id="'.$data->id.'"
class="btnedit btn btn-primary btn-sm">Edit</button></a>';
$button.= '<form action="user/'.$data->id.'
" method="post">
'.csrf_field().'
'.method_field('DELETE').'
<button type="submit" name="delete" id="'.$data->id.'"
class="btndelete btn btn-danger btn-sm">Delete</button></form>';
return $button;
});
}
/**
* Displays the list of users according to the usertype
*
* #param \App\User $user
*/
public function getUserByType($user)
{
if($user->usertype === 'super admin')
{
$users=$user->isSuperAdmin();
}
elseif($user->usertype === 'admin')
{
$users=$user->isAdmin();
}
elseif($user->usertype === 'user')
{
$users=$user->isUser();}
else
{
abort(404);
//throw new Exception('Not Authorized');
}
return $users;
}
/**
* Get query source of dataTable.
*
* #param \App\User $user
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(User $user)
{
$user=auth()->user();
$users=$this->getUserByType($user);
return datatables()->of($users);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->setTableId('user')
->columns($this->getColumns())
->minifiedAjax()
->dom('frltip');
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('id'),
Column::make('name'),
Column::make('email'),
Column::make('usertype'),
Column::make('created_at'),
Column::make('action')->width('20%'),
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
//return 'Users_' . date('YmdHis');
}
}
There are no changes in the controller , it remains the same , however the problem is solved using function in which i filtered out the query according to the authenticated user
you have to add the following in the model, u can also do it your way, this is not necessary.
/**
* Shows the list of users when super admin is logged in
*
*/
public function isSuperAdmin()
{
return $this->where('usertype','<>','Super Admin');
}
/**
* Shows the list of users when admin is logged in
*
*/
public function isAdmin()
{
return $this->where('usertype','<>','Super Admin')->where('usertype','<>','Admin') ;
}
/**
* Shows the list of users when user is logged in
*
*/
public function isUser()
{
return $this->where('usertype','candidate');
}

form request validation in laravel 6 and vue does not triggering anything

I'm working in laravel 6 and vueJs; I want to validate the form request using the custom laravel form request. But it does not trigger any validation error instead gives this error message (500 (Internal Server Error)).
this my code. if anyone could help me would be greatly appreciated.
signup.vue
<template>
<v-container>
<v-form #submit.prevent="signup" class="signup-form">
<v-text-field
label="Name"
v-model="form.name"
type="text"
required
></v-text-field>
<v-text-field
label="E-mail"
v-model="form.email"
type="email"
required
></v-text-field>
<v-text-field
label="Password"
v-model="form.password"
type="password"
required
></v-text-field>
<v-text-field
label="Password_confirmation"
v-model="form.Password_confirmation"
type="password"
required
></v-text-field>
<v-btn type="submit" color="green">signup</v-btn>
<router-link to="/login">
<v-btn color="blue">Login</v-btn>
</router-link>
</v-form>
</v-container>
</template>
<script>
export default {
data() {
return {
form: {
name: null,
email: null,
password: null,
password_confirmation: null
}
}
},
errors: {},
methods: {
signup() {
axios.post('/api/auth/signup', this.form)
.then(res => this.responseAfterLogin(res))
.catch(error => console.log(error.response.data))
}
},
}
</script>
<style>
.signup-form {
margin-top: -120px;
margin-bottom: 15px;
}
</style>
Auth controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\SignupRequest;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('JWT', ['except' => ['login', 'signup']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Signup part added manually
*/
public function signup(Request $request)
{
$data = $request->validate([
'name' => 'required',
'email' => 'required|string',
'password' => 'required|string',
]);
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'username' => auth()->user()->name,
]);
}
}
SignupRequest:
<?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',
'email' => 'required',
'password' => 'required|confirmed',
];
}
}
You must define SignupRequest class on your controller for work defined rules. Example usage for signup function,
public function signup(SignupRequest $request)
{
User::create($request->all()); // the problem is not bcrypting the password section
// login the registered user
return $this->login($request);
}
Also you should define $token variable on login function.
Finally, you can find error details on under storage/logs/ folder files.
I hope this help you.

How to allow guest users to view posts, without having to login

I am trying to make Guests users i.e users that are not logged in to view some posts.
I have tried to add Guest Auth but it is not working. Also i will love to get the URL link to the post as slug instead of ID
E.g localhost:8000/news/1 should be localhost:8000/news/post-title
<?php
namespace App\Http\Controllers;
use App\News;
use Illuminate\Http\Request;
class NewsController extends Controller
{
function __construct()
{
$this->middleware('auth', ['except' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$news= News::paginate(15);
return view('categories.news',compact('news'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('news.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//validate
$this->validate($request,[
'subject'=>'required|min:10',
'body' => 'required|min:20'
]);
//store
auth()->user()->news()->create($request->all());
//redirect
$news= News::paginate(15);
return view('categories.news', compact('news'));
}
/**
* Display the specified resource.
*
* #param \App\News $news
* #return \Illuminate\Http\Response
*/
public function show(News $news)
{
return view('news.single', compact('news'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\News $news
* #return \Illuminate\Http\Response
*/
public function edit(News $news)
{
return view('news.edit', compact('news'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\News $news
* #return \Illuminate\Http\Response
*/
public function update(Request $request, News $news)
{
if(auth()->user()->id !== $news->user_id){
abort(401, "Please Login");
}
$this->validate($request,[
'subject'=>'required|min:10',
'body' => 'required|min:20'
]);
$news->update($request->all());
return redirect()->route('news.show', $news->id)->withMessage('News Updated');
}
/**
* Remove the specified resource from storage.
*
* #param \App\News $news
* #return \Illuminate\Http\Response
*/
public function destroy(News $news)
{
if(auth()->user()->id !== $news->user_id){
abort(401, "Please Login");
}
$news->delete();
$news= News::paginate(15);
return view('categories.news', compact('news'));
}
}
This is the single post blade that i will like guest users to be able to view.
<div class="main-body">
<div class="clearfix">
<div class="main-body-content text-left">
<h1 style="font-size: 20px;font-weight: 800;" class="post-title">{{$news->subject}}</h1>
<h5>By {{ Auth::user()->name }}</h5>
<div class="post-body">
<p>{!! $news->body !!}</p>
</div>
#if(auth()->user()->id==$news->user_id)
<div class="all-edit">
<div class="post-body">
(Edit)
</div>
<div class="delete">
<form action="{{route('news.destroy',$news->id)}}" method="POST">
{{csrf_field()}}
{{method_field('DELETE')}}
<input type="submit" value="Delete">
</form>
</div>
</div>
#endif
</div>
</div>
</div>
you have to remove this route from middleware of "auth".

Laravel cannot display a selected product details

maybe someone can help me. I have done a product list from my database. It shows product image, title, content, price
When I select on one of the products, it opens in the new window. And I cant see any product details (no image, no title, no content) , just empty page.
See all attachments:
my BrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\file;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Collection;
class BracController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('insertBrac');
}
public function showBrac()
{
$user=file::all();
return view('apyrankes', compact('user'));
}
public function view_brac()
{
$object = \DB::table('braclets')->where('BrackID' , request('brackId'))->first();
return view('view_object', array('user' => $object));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
{
$user = new file;
$user->Title= Input::get('title');
$user->Content= Input::get('content');
$user->Price= Input::get('price');
if (Input::hasFile('image'))
{
$file=Input::file('image');
$file->move(public_path(). '/uploads', $file->getClientOriginalName());
$user->Image = $file->getClientOriginalName();
}
$user->save();
return redirect( "insertBrac" );
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My product list:
apyrankes.blade.php
<div class="header">
#include('header')
</header>
<body>
<div class="content-products">
#foreach($user as $users)
<div id="myDiv">
<div class="products">
<img src="{{ $users->Image}}" alt="{{ $users->Title}}" width="200px" height="200px"><br>
{{ $users->Title}}<br>
{{ $users->Content}}<br>
{{ $users->Price}}€<br>
Plačiau
</div>
</div>
#endforeach
</div>
</body>
And when I select one of the product from product list on apyrankes.blade.php
it opens in view_object.blade.php , but I cannot see there any details of the select product, just empty page:
My view_object.blade.php
<div class="header">
#include('header')
</header>
<body>
<Br>
<br>
<Br>
<div class="content-products">
<div id="myDiv">
<div class="products">
#if($user)
<img src="{{ $user->Image}}" alt="{{ $user->Title}}" width="200px" height="200px"><br>
{{ $user->Title}}<br>
{{ $user->Content}}<br>
{{ $user->Price}}€<br>
#endif
</div>
</div>
</div>
</body>
Because you did
Plačiau</div>
The name of the variable you need to fetch is product
$object = \DB::table('braclets')->where('BrackID' , request('product'))->first();

Registration process runs normally but login view is not working laravel authentication

I am new to laravel. i have seen some related posts but i could not find right answer. I made an auth using php artisan make:auth, i have a directory publicPages. I have changed the auth.login view to my custom publicPages.login and publicPages.register. Registration process works fine, inserts the data into users table. but it does not login the user. When i go to login view and enter credentials. It neither give any error nor log the user in. just redirects it to back.
Here are routes:
Route::auth();
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Route::group(array('namespace' => 'UserControllers'), function()
{
Route::group(['middleware' => ['web']], function() {
Route::group(['middleware' => 'auth'], function () {
Route::get('community', 'UserController#showCommunity');
Route::post('communities', 'UserController#addCommunity');
Route::get('edit/{id}', ['as' => 'edit', 'uses' => 'UserController#editCommunity']);
Route::get('delete/{id}', 'UserController#deleteCommunity');
Route::post('update/{id}', ['as' => 'update', 'uses' => 'UserController#updateCommunity']);
Route::get('create', 'IdeaController#displayPost');
Route::post('idea', 'IdeaController#storePost');
Route::get('users', 'UserController#showUserListing');
Route::get('deleteUser/{id}', 'UserController#deleteUser');
Route::get('delete/idea/{id}', 'IdeaController#deleteIdea');
Route::get('approve/{id}', 'IdeaController#approveIdea');
});
});
Controller:
class UserController extends Controller {
//constructor
public function __construct() {
$this->middleware('auth');
}
I know when i would use $this->middleware('auth'); it would redirect to login page for every UserController function. which is working fine.
View:
<form id="login-form" class="clearfix" action="{{url('/login')}}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<p class="rs pb30">Please Provide your Credentials to Verify Your Identity</p>
<div class="form form-post-comment">
<div class="fa-align-center">
<label for="login_email">
<input id="login_email" type="email" name="email" class="txt fill-width txt-name{{ $errors->has('email') ? ' has-error' : '' }}" placeholder="Enter Your Email" required="required"/>
</label>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
<br><br>
<label for="password">
<input id="password" type="password" name="login_password" class="txt fill-width txt-email" placeholder="Enter Your Password" required="required"/>
</label> <br><br>
<label for="links">
Forgotten Password?
<p>Don't have an account? Register Here </p>
</label>
</div>
<div class="clear"></div>
<p >
<span id="response"></span>
{{--<input type="submit" class="btn btn-submit-comment" value="Login">--}}
<button class="btn btn-submit-comment" form="login-form">Login</button>
</p>
</div>
Here is AuthenticatesUsers file:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
//use App\Http\Requests\UserRequest;
trait AuthenticatesUsers
{
use RedirectsUsers;
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function getLogin()
{
return $this->showLoginForm();
}
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$view = property_exists($this, 'loginView')
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {
return view($view);
}
return view('publicPages.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
return $this->login($request);
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// 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.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// 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.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Get the failed login message.
*
* #return string
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? Lang::get('auth.failed')
: 'These credentials do not match our records.';
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only($this->loginUsername(), 'password');
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
return $this->logout();
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
/**
* Get the guest middleware for the application.
*/
public function guestMiddleware()
{
$guard = $this->getGuard();
return $guard ? 'guest:'.$guard : 'guest';
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'email';
}
/**
* Determine if the class is using the ThrottlesLogins trait.
*
* #return bool
*/
protected function isUsingThrottlesLoginsTrait()
{
return in_array(
ThrottlesLogins::class, class_uses_recursive(static::class)
);
}
/**
* Get the guard to be used during authentication.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
is There anything i need to change in postLoginForm() ? Thanks
update 2:
I have changed postLoginForm() function's code to
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
} else {
echo 'not logged in';
}
now finally it prints not logged in but even i use true credentials it says not logged in,
Try to remove web middleware from routes.php, because it applies automatically since 5.2.27 and if you apply it manually it can cause errors similar to yours.
According to your routes file, your login route is /auth/login not /login. So I suggest you to change the action in your view file as:
action="{{url('/auth/login')}}"
EDIT
Since Route::auth(); is already added at the top of your routes file,
you do not need following in your routes file:
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Please remove that and revert the url in login form.

Resources