I am creating the simple login form using laravel 7.i want to check the username and password match.it is a match redirect the home. if it does not redirect the login page again show the error username or password does not match. I tried the below code I got the error Call to undefined method App\User::attempt()
Login Controller.
public function check(Request $request)
{
$uname = $request->uname;
$password = $request->password;
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
if (User::attempt(array('uname' => $uname , 'password' => $password ))){
return "success";
}
else {
return "Wrong Credentials";
}
}
view Login
#extends('layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Login</h2>
</div>
<div class="pull-right">
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="row">
<form action="{{ route('login.check') }}" method="POST">
#csrf
<div class="col-sm-4">
<div class="left">
<strong>UserName</strong>
<input type="text" name="uname" class="form-control" placeholder="UName">
</div>
<div class="left">
<strong>Password</strong>
<input type="password" class="form-control" name="password" placeholder="Password"></textarea>
</div>
</br>
<div class="left">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
Model User
protected $fillable = [
'name', 'email', 'password',
];
you need to replace User::attempt with auth()->attempt
another thing you don't need to check uname and passowrd manually laravel do that for you inside the attempt method so it would be more efficient if
you delete those two lines
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
finally, depends on your User model you have name not uname so you need to update it like this
if (auth()->attempt(array('name' => $uname , 'password' => $password ))){
return "success";
} else {
return "Wrong Credentials";
}
Related
I want to validate all field. But It is validating only first field. Append field is not validating
multiple fields validation using livewire? name.0.required is working but name.*.required is not working.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Test extends Component
{
public $name;
public $inputs = [];
public $i = 1;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->inputs ,$i);
}
public function remove($i)
{
unset($this->inputs[$i]);
}
public function store()
{
$validatedDate = $this->validate([
'name.0' => 'required',
'name.*' => 'required',
],
[
'name.0.required' => 'name field is required',
'name.*.required' => 'name field is required',
]
);
session()->flash('message', 'Name Has Been Created Successfully.');
}
public function render()
{
return view('livewire.test');
}
}
<div>
<form class="offset-md-3">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
#error('name.0') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
</div>
</div>
</div>
#foreach($inputs as $key => $value)
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
#error('name.'.$value) <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove</button>
</div>
</div>
</div>
#endforeach
<div class="row">
<div class="col-md-12">
<button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Save</button>
</div>
</div>
</form>
</div>
This is my full code use to create multi field using livewire. I am not able to validate appended field so I need help to solve this problem. This validate first field name.0 other append field name.* does not validate.
You should use $key instead $value.
Like this:
wire:model="name.{{ $key }}"
With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form
I am a beginner and I am trying to make validation for the user assigned when I assign the same user again when I submit so the error message should be shown, this user is already assigned please help me how to do this? thanks.
Controller
public function adduseraction(REQUEST $request) {
// Users_permissions::where('user_id',$request->userid)->get()-
// >pluck('user_Access_id');
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
html view
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<label>Select User</label>
<select name="userid" class="form-control" id="typeofworkday">
<option>Select User</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<br> <br> <br>
<div class="card-body">
<label>Select Muliple User or One</label>
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" id="check" name="multiusersid[]" value="
{{$user->id}}" class="form-check-input" >
<h5 style="position:relative;left:10px;">{{$user->name}}</h5>
</div>
<!-- checkbox -->
</div>
#endforeach
</div>
<!-- /.card-body -->
</div>
<br><br><br><br>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-
md-2 center">Submit</button>
</div>
</form>
Ok you can do something like below
First check does user already exists in the table and if exists return redirect with the error message or else insert the data
public function adduseraction(Request $request) {
$isUserAvailable = Users_permissions::where('user_id',$request->userid)->get()- >pluck('user_Access_id');
//If user already exists
if($isUserAvailable) {
return redirect('admin')->with('error', 'Users has been assigned');
}else{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
}
I am using middleware for user roles.
But when I am using middleware in Controller __construct method, request validation does not work properly. It doesnt show any errors, session error bag returns null. I am not able to see any errors when form submit. But when I have disabled middleware in construct I can see request validation errors.
web.php middleware + controller _construct middleware = request validation doesnt works.
web.php middleware + without _construct middleware = works fine.
without web.php middleware + _construct middleware = works fine.
I showed the details in my codes.
I tried every method for a week but I couldn't solve it.
I look forward to your help sincerely.
web.php
Route::group(['middleware' => ['client.role:paying']], function () {
Route::get('/pay_section', 'HomepageController#showPaySection');
Route::get('/pay_success', 'HomepageController#showPaySuccess');
Route::get('/pay_error', 'HomepageController#showPayError');
Route::post('/pay_section', 'HomepageController#doPaySection');
});
HomepageController (like this my form request validation doesnt works because of middleware)
public function __construct()
{
$this->middleware(function ($request, $next) {
$client = auth()->guard('client');
if ($client->check()){
$request->session()->put('client_id', $client->user()->id);
}else{
$request->session()->put('client_id', -1);
}
$this->_cid = $request->session()->get('client_id'); // client
View::share(['cid' => $this->_cid]);
return $next($request);
});
}
HomepageController (like this my codes works perfect. I am able to see request validation errors there is no problem.)
public function __construct()
{
$this->_cid = 2; // client
View::share(['cid' => $this->_cid]);
}
Middleware ClientRole.php
public function handle($request, Closure $next, ...$roles)
{
$currentRole = array();
$client = auth()->guard('client');
if ($client->check()){
$currentRole[] = 'client';
}else{
$currentRole[] = 'guest';
}
if (session()->has('shop_cart')) {
$currentRole[] = 'shopping';
}
if (session()->has('order')) {
$currentRole[] = 'paying';
}
$currentRole[] = 'paying';
foreach($roles as $role) {
if(in_array($role, $currentRole))
return $next($request);
}
return redirect('/');
}
HomepageController form action
public function doPaySection(CreditcardRequest $request)
{
$validated = $request->validated();
// it doesnt show any errors when form empty. But it should be.
// without middleware it shows error on my view when form empty.
}
View
<div class="messages">
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Error!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
</div>
<form action="{{ action('HomepageController#doPaySection') }}" method="post"
class="needs-validation" novalidate>
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<label for="ccname">Name on card</label>
<input type="text" class="form-control" name="cc_name" id="ccname" placeholder="" value="" required>
<small class="text-muted">Full name as displayed on card</small>
<div class="invalid-feedback">
Name on card is required
</div>
</div>
<div class="col-md-6 mb-3">
<label for="ccnumber">Credit card number</label>
<input type="text" class="form-control" name="cc_number" id="ccnumber" placeholder="" value="" >
<div class="invalid-feedback">
Credit card number is required
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 mb-3">
<label for="ccexp">Expiration</label>
<input type="text" class="form-control" name="cc_exp" id="ccexp" placeholder="" value="1209" required>
<div class="invalid-feedback">
Expiration date required
</div>
</div>
<div class="col-md-3 mb-3">
<label for="cccvv">CVV</label>
<input type="text" class="form-control" name="cc_cvv" id="cccvv" placeholder="" value="333" required>
<div class="invalid-feedback">
Security code required
</div>
</div>
</div>
<hr class="mb-4">
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">
<i class="fa fa-check"></i> Submit
</button>
</form>
You may set SESSION_DRIVER=file in you .env file
Then run php artisan config:clear
Seems related
I'm succeed to send mail from contact form, and now my requirement is to get automated success reply to the users input email address when submitting the form. please help me on this
ContactUsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactUs;
class ContactUsController extends Controller
{
function index()
{
return view('home/contactus');
}
function send(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'subject' => $request->subject,
'message' => $request->message
);
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
return back()->with('success', 'Thanks for contacting us! We will get back to you soon.');
}
}
ContactUs
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactUs extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->from('xxxx#mail.com')
->subject('Customer Feedback')
->view('dynamic_email_template')
->with('data', $this->data);
}
}
Form
<div class="form">
<h4>Send us a message</h4>
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data- dismiss="alert">×</button>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data- dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
<form method="post" action="{{url('contactus/send')}}" autocomplete="off">
{{ csrf_field() }}
<div class="form-group">
<input type="text" name="name" for="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" for="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" for="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" for="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center">
<button type="submit" name="send" title="Send Message">Send Message</button>
</div>
</form>
</div>
dynamic_email_template
<p>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</p> </br>
<p>{{ $data['subject'] }}</p> </br>
<p>I have some query like "{{ $data['message'] }}".</p> </br>
<p>It would be appriciative, if you gone through this feedback.</p>
You need to create email template same like your view file, lets say contact_us_email.blade.php. In this file add this content
contact_us_email.blade.php
<html>
<body>
<h2>Hi, This is {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Subject: {{ $data['subject'] }}</p> <br>
<p>I have some query like <b>"{{ $data['message'] }}"</b>. <br>
<p>It would be appriciative, if you gone through this feedback.</p>
</body>
</html>
NOTE: Add css or styling according to your need. this is basic html
Edit: To send confirmation email to user
For success confirmation to user, you can create another email template like
contact_us_thank_you_email.blade.php
<html>
<body>
<h2>Hello, {{ $data['name'] }} "{{ $data['email'] }}"</h2><br>
<p>Thank You for your interest...blah blah blah</p> <br>
<p>Our team will contact you soon</p> <br>
</body>
</html>
Now in your ContactUsController, replace
\Mail::to('xxx#mail.com')->send(new ContactUs($data));
with
Mail::send('contact_us_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to('xxx#mail.com')->subject($data['subject']);
});
Mail::send('contact_us_thank_you_email', $data, function ($message) use ($data) {
$message->from('xxx#mail.com', 'xxx');
$message->to($data['email'])->subject('Thank you for the interest');
});
And I think you are good to go with this. I hope this is what you are asking for.