I would like someone to explain to me why I'm getting undefined variable errors when I run my phpunit tests from my Laravel application. I have if statements set up so that it doesn't add them by default so not sure why.
<?php
Route::auth();
Route::group(['middleware' => 'web'], function () {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'HomeController#dashboard']);
});
<form role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group form-material floating {{ $errors->has('email') ? 'has-error' : '' }}">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}"/>
<label for="email" class="floating-label">Email</label>
#if ($errors->has('email'))
<small class="help-block">{{ $errors->first('email') }}</small>
#endif
</div>
<div class="form-group form-material floating {{ $errors->has('password') ? 'has-error' : '' }}">
<input id="password" type="password" class="form-control" name="password" />
<label for="password" class="floating-label">Password</label>
#if ($errors->has('password'))
<small class="help-block pull-left">{{ $errors->first('password') }}</small>
#endif
</div>
<div class="form-group clearfix">
<div class="checkbox-custom checkbox-inline checkbox-primary checkbox-lg pull-left">
<input type="checkbox" id="inputCheckbox" name="remember">
<label for="inputCheckbox">Remember me</label>
</div>
<a class="pull-right" href="{{ url('/password/reset') }}">Forgot password?</a>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg margin-top-40">Log in</button>
</form>
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends TestCase
{
use WithoutMiddleware;
/** #test */
public function user_can_visit_login_page()
{
$this->visit('login');
}
/** #test */
public function user_submits_form_with_no_values_and_returns_errors()
{
$this->visit('login')
->press('Log in')
->seePageIs('login')
->see('The email field is required.')
->see('The password field is required.');
}
/** #test */
public function it_notifies_a_user_of_wrong_login_credentials()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type('notmypassword', 'password')
->press('Log in')
->seePageIs('login');
}
public function user_submits_login_form_unsuccesfully()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type($user->password, 'password')
->press('Log in')
->seePageIs('dashboard');
}
}
Errors Given
1) LoginTest::user_can_visit_login_page
A request to [http://myapp.app/login] failed. Received status code [500].
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:61
/Users/me/Projects/repositories/MyApp/tests/LoginTest.php:13
Caused by
exception 'ErrorException' with message 'Undefined variable: errors' in /Users/me/Projects/repositories/MyApp/storage/framework/views/cca75d7b87e55429621038e76ed68becbc19bc14.php:30
Stack trace:
Remove the WithoutMiddleware trait from your test.
Related
I'm just new to laravel and I couldn't understand why the error message of validation won't display and it redirect instead to "419|page expired" , even after following a video tutorial and the laravel documentation.
*This is the html code
<form action="{{ route('registerPost') }}" method="post">
<!-- full name div -->
<div class="flex mt-2 gap-2">
<div class="w-1/2">
<label for="">First Name</label><br>
<input id="firstName" class="w-full px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:border-green-500" type="text" name="firstName" value="">
</div>
#error('firstName')
<div class="text-sm text-red">{{ $message }}</div>
#enderror
<div class="w-1/2">
<label for="">Last Name</label><br>
<input class="w-full px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:border-green-500" type="text" name="lastName" value="">
</div>
</div>
*The route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\createController;
Route::get('/', function () {
return view('logIn');
});
Route::get('/register', [createController::class, 'index'])->name('register');
Route::post('/register', [createController::class, 'store'])->name('registerPost');
*Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class createController extends Controller
{
public function index(){
return view('register');
}
public function store(Request $request)
{
$validated = $request->validate([
'firstName' => 'required|max:30',
'lastName' => 'required|max:30',
'email' => 'required|max:30',
'username' => 'required|max:30',
'password' => 'required|max:30'
]);
}
}
try to add .
{{ csrf_field() }}
Add #csrf
Or
{{ csrf_field() }}
into the form tag
In hyn/multi-tenancy after overriding the login method in LoginController and within this method connect the tenant database. It login successfully if I print the login results but when I redirect it to homeController it again redirects to the Login Page and doesn't go to the home page. I use
https://github.com/peartreedigital/boilerplate
example only change in loginController which is
class LoginController extends Controller
{
use AuthenticatesUsers;
public function username()
{
$login = request()->input('identity');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function validateLogin(Request $request)
{
$messages = [
'identity.required' => 'Email or username cannot be empty',
'email.exists' => 'Email or username already registered',
'username.exists' => 'Username is already registered',
'password.required' => 'Password cannot be empty',
];
$request->validate([
'identity' => 'required|string',
'password' => 'required|string',
'email' => 'string|exists:users',
'username' => 'string|exists:users',
], $messages);
$domain_name = $request->get('domain_name');
$usernameatacc = $request->get('identity');
$password = $request->get('password');
$hostname = DB::table('hostnames')->select('*')->where('fqdn', $domain_name)->first();
$dbname = DB::table('websites')->select('uuid')->where('id', $hostname->website_id)->first();
Config::set("database.connections.tenant", [
"driver" => 'mysql',
"host" => '127.0.0.1',
"database" => $dbname->uuid,
"username" => 'root',
"password" => ''
]);
Config::set('database.default', 'tenant');
DB::purge('tenant');
DB::reconnect('tenant');
}
public function login(Request $request)
{
$this->validateLogin($request);
$user_data = User::where('email', $request->get('identity'))
->first();
$matchPwd = Hash::check($request->get('password'), $user_data->password);
if ($matchPwd == '1') {
// print_r($user_data);
// Here What can I do????? Please help
}else {
return redirect()->back()->withErrors($user_data);
}
}
protected function guard()
{
return Auth::guard();
}
}
My login form in login.blade.php is
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="domain_name" class="col-sm-4 col-form-label text-md-right">{{ __('Domain Name') }}</label>
<div class="col-md-6">
<input id="domain_name" type="domain_name" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="domain_name" value="{{ old('domain_name') }}" required autofocus>
#if ($errors->has('domain_name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('domain_name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-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="identity" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
You can redirect user after login with defining either method of redirectTo() or property of $redirectTo.
protected function redirectTo()
{
if (User::check()) {
return route('home');
}
}
or
protected $redirectTo = '/';
Be careful about referring to the name that you've assigned in the route file (default: web.php).
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.
I have generated user auth through make:auth, which doesn't have edit details field, now I want to edit details such as email and contact, and others leave as disabled. I have tried to copy code from RegisterController i just changed create method to update method, If you have ready template for edit details please share me, I have searched many ready templates but not found, I just want template, which will be compatible with generated Auth or solution to my problem, because now it is not updating the details
1) View: edit_profile.blade.php
<form method="POST" action="/profile">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" disabled type="text" class="form-control" value='{{$user->name}}' name="name">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Student Number') }}</label>
<div class="col-md-6">
<input id="username" disabled type="text" class="form-control" name="username" value="{{$user->username}}">
</div>
</div>
<div class="form-group row">
<label for="age" class="col-md-4 col-form-label text-md-right">{{ __('Age') }}</label>
<div class="col-md-6">
<input id="age" disabled type="text" class="form-control" name="age" value="{{$user->age}}"
required> #if ($errors->has('age'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('age') }}</strong>
</span> #endif
</div>
</div>
<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="{{$user->email}}"
required> #if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-md-4 col-form-label text-md-right">{{ __('Contact Number') }}</label>
<div class="col-md-6">
<input id="contact" type="text" class="form-control{{ $errors->has('contact') ? ' is-invalid' : '' }}" name="contact" value="{{$user->contact}}"
required> #if ($errors->has('contact'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('contact') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Update Details') }}
</button>
</div>
</div>
</form>
2) Controller: ProfileController
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Image;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Carbon;
class ProfileController extends Controller
{
public function profile(){
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->crop(300, 300)->save( public_path('/storage/images/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'contact' => 'numeric|digits_between:7,15',
]);
}
public function edit(){
return view('pages.profiles.edit_profile', array('user' => Auth::user()) );
}
public function update(array $data){
return User::update([
'email' => $data['email'],
'contact' => $data['contact'],
]);
}
}
Routes
//User Profile
Route::get('/profile', 'ProfileController#profile');
Route::post('profile', 'ProfileController#update_avatar');
Route::get('/profile/edit', 'ProfileController#edit');
Route::post('profile/edit', 'ProfileController#update');
There are a few issues that I've noticed.
You're ProfileController#update method accepts an array but it won't be getting passed an array.
You're not calling update on the authenticated user.
You're posting to /profile which looking at your routes if for updating the avatar and not the user data.
Change your form to be:
<form method="POST" action="/profile/edit">
Change your update method to:
public function update(Request $request)
{
$data = $this->validate($request, [
'email' => 'required|email',
'contact' => 'required',
]);
auth()->user()->update($data);
return auth()->user();
}
Documentation for Laravel's Validation
public function update(Request $request)
{
//check validation
Auth::user()->update($request);
return true;
}
I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.