Here is my content.blade.php
<form action="{{ route('home') }}" method="post">
<input class="input-text" type="text" name="name" value="Your Name *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<input class="input-text" type="text" name="email" value="Your E-mail *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<textarea name="text" class="input-text text-area" cols="0" rows="0" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">Your Message *</textarea>
<input class="input-btn" type="submit" value="send message">
{{ csrf_field() }}
</form>
That's my routes(web.php)
Route::group(['middleware'=>'web'], function(){
Route::match(['get', 'post'], '/', ['uses'=>'IndexController#execute', 'as'=>'home']);
Route::get('/page/{alias}', ['uses'=>'PageController#execute', 'as'=>'page']);
Route::auth();
});
And Finally here is my IndexController.php, method execute():
if($request->isMethod('post')){
$messages = [
'required' => "Поле :attribute обязательно к заполнению",
'email' => "Поле :attribute должно соответствовать email адресу"
];
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'text' => 'required'
], $messages);
dump($request);
}
So, the problem is that dump($request) does not work, and I also tried to comment everything except dump($request), and the result is the same. I think it just skips if($request->isMethod('post')) so that it returns that the method is not true, may be there is something wrong with token, I am not sure.
How to resolve this issue?
edit:
That's the code above if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Page;
use App\Service;
use App\Portfolio;
use App\People;
use DB;
class IndexController extends Controller
{
//
public function execute(Request $request){
You should assign $request to somewhere first.
For example, if i have a store method and i have to use Request $request for grabbing the information, i should establish it first, so by establishing it my application will recognize what does the variable is retrieving, let me show you an example code:
public function store(Request $request)
{
$data = $request->all();
$data['a'] = Input::get('a');
$data['b'] = Input::get('b');
$data['c'] = Input::get('c');
$data['d'] = Input::get('d');
$data['e'] = Input::get('e');
Letters::create($data);
return redirect::to('/');
}
Did you get it?
If not, here is an example with isMethod:
$method = $request->method();
if ($request->isMethod('post')) {
//
}
In your code i did not see the $var = $request->method(); (or what you want it to be).
Related
I have a webpage with 4 different urls
www.sample.com\home
www.sample.com\about
www.sample.com\products
www.sample.com\contact
I have a contact form in all the pages of my webpage.
I need to know the Page, from where the contact form is submitted from either(home, about, products or services).
I use laravel mailer to send mail, once the contact form is submitted.
Contact form:
<input type="hidden" name="url" value="{{substr(strrchr(url()->current(),'/'),1)}}">
<form method="POST" action="sendEmail">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="{{ old('name') }}" />
<label for="email">Email</label>
<input type="email" name="email" id="email" value ="{{ old('email') }}"/>
<label for="message">Message</label>
<textarea name="body" id="message" rows="5"> {{ old('message') }}</textarea>
<button class ="primary"> Submit </button>
</form>
Controller:
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = PostRequest::input('url');
\Mail::send('E-mail view', $data, $currentPage, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}
I need the URL as home, about, products, contact, from where the Contact form is submitted from not the form action sendEmail inside the E-mail View blade file
Email View Blade:
<p> $name </p>
<p> $email</p>
<p> $currentPage </p>
It throws an Error
Function name must be a string
How to pass the current URL from Where the Form is submiited from (home, about,..) to Mail?
Could anyone please help?
Many thanks.
Try like this
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = request()->url();
$data['currentPage'] = $currentPage;
\Mail::send('E-mail view', $data, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}
I am trying to implement Laravel's default email verification but whenever I change column name of users table from email to user_email Laravel stop sending verification email.
I also override default method getEmailForVerification() found in MyVerifyEmail.php file in my User Model that is returning user_email correctly.
My User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
public function getAuthPassword ()
{
return $this->user_password;
}
protected $primaryKey = 'user_id';
protected $fillable = [
'user_name',
'user_email',
'user_password',
'user_phone',
'user_role_id',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = ['email_verified_at' => 'datetime',];
public function getEmailForVerification()
{
return $this->user_email;
}
public function role()
{
return $this->belongsTo(Role::class , 'user_role_id');
}
}
RegisterController Code:
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'email'=>'required |email|unique:App\Models\User,user_email',
'password'=>'required',
'phone'=>'required|unique:App\Models\User,user_phone|min:10|max:15'
]);
$user = User::create([
'user_name' => $request->name,
'user_email' => $request->email,
'user_password' => Hash::make($request->password),
'user_phone' => $request->fullMobileNumber,
'user_role_id' => '9'
]);
event(new Registered($user));
$query = $user->save();
if($query){
$request->session()->flash('success','Your account has been created successfully');
return redirect()->route('login');
}
else{
return back()-> with('failed','Something went wrong. Please try again');
}
}
public function emailVerificationNotice()
{
return view('auth.verifyEmail');
}
public function emailVerificationVerify(EmailVerificationRequest $request)
{
$request->fulfill();
return redirect()->route('dashboard');
}
Register.blade.php
<form action="{{route('auth.store')}}" method="POST" id="user-registration" data-parsley-validate>
#csrf
<div id="name-wrapper" class="form-group parsley-input">
<label>Full name<span class="tx-danger">*</span></label>
<input type="text" name="name" class="form-control" placeholder="Enter your full name"
data-parsley-class-handler="#name-wrapper" data-parsley-required-message="Please enter your full name"data-parsley-pattern="^[a-zA-Z \s]+$"
data-parsley-pattern-message="Numbers & special characters aren't allowed"required>
<p class="text-danger">#error('name'){{$message}}#enderror</p>
</div>
<div id="email-wrapper" class="form-group parsley-input">
<label>Email address<span class="tx-danger">*</span></label>
<input type="email" name="email" class="form-control" placeholder="Enter your email address"
data-parsley-required-message="Please enter your email address" required autocomplete="off">
<p class="text-danger">#error('email'){{$message}}#enderror</p>
</div>
<div id="password-wrapper" class="form-group parsley-input">
<label>Password<span class="tx-danger">*</span></label>
<input type="password" name="password" class="form-control" placeholder="Enter your password"
data-parsley-required-message="Please enter your password" data-parsley-pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,}$"
data-parsley-pattern-message="Password must be 6-50 chars long, at least one letter & one number" required >
<p class="text-danger">#error('password'){{$message}}#enderror</p>
</div>
<div id="phone-wrapper" class="form-group parsley-input">
<label>Mobile number<span class="tx-danger">*</span></label>
<input type="tel" name="phone" id="user-phone" class="form-control" required>
<p id="phone-error-null" class="d-none">Please enter mobile number</p>
<p id="phone-error-msg" class="d-none"></p>
<p class="text-danger">#error('phone'){{$message}}#enderror</p>
</div>
<div class="form-group tx-12">
By clicking <strong>Create an account</strong> below, you agree to our terms of service and privacy statement.
</div><!-- form-group -->
<button type="submit" id="submit-registration" class="btn btn-brand-02 btn-block">Create Account</button>
</form>
.ENV Config
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=c1952edd7b2969
MAIL_PASSWORD=3376437f06507d
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=from#example.com
MAIL_FROM_NAME="${APP_NAME}"
actually the issue get from while overriding function getEmailForVerification().
so, i recommended you to make file MustVerifyEmail.php on Model
then copy all code from Illuminate\Contracts\Auth\MustVerifyEmail from this file and paste on new file. then use your code on new file like
public function getEmailForVerification()
{
return $this->user_email;
}
and dont forget to change User.php file
like replace
use Illuminate\Contracts\Auth\MustVerifyEmail;
to
use App\Models\MustVerifyEmail;
I am trying to work on a Laravel PHP project and as I am new to this framework. First step I had to do is build a Registration Form. However, when I click on the Submit button no error is given, and nothing is registered in my users table.
Here is the code for my project so far :
My users migration table up and down functions
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->boolean('sexe');
$table->integer('age');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
I added to the original two fields which are : "sexe a boolean F/M" and age
My RegisterController important functions
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Mail;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/register';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required', 'string', 'max:255',
'sexe'=> 'required|in:male,female',
'age' => 'required|integer|max:100',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users',
'password' => 'required', 'string', 'min:5', 'confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'sexe' => $data['sexe'],
'age' => $data['age'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
/**
* Override default register method from RegistersUsers trait
*
* #param array $request
* #return redirect to $redirectTo
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
//add activation_key to the $request array
$activation_key = $this->getToken();
$request->request->add(['activation_key' => $activation_key]);
$user = $this->create($request->all());
//$this->guard()->login($user);
//write a code for send email to a user with activation link
$data = array('name' => $request['name'], 'email' => $request['email'], 'activation_link' => url('/activation/' . $activation_key));
Mail::send('emails.mail', $data, function($message) use ($data) {
$message->to($data['email'])
->subject('Activate Your Account');
$message->from('s.sajid#artisansweb.net');
});
return $this->registered($request, $user)
?: redirect($this->redirectPath())->with('success', 'We have sent an activation link on your email id. Please verify your account.');
print_r($request->input());
}
}
My Routes
Route::auth();
Route::get('/home', 'HomeController#index');
Auth::routes();
Route::get('/register', 'RegisterController#create');
Route::post('/register', 'RegisterController#register');
Route::get('/', function () {
return view('welcome');
});
My User.php Model fillable
protected $fillable = [
'name','sexe','age','email','password',
];
protected $hidden = [
'password', 'remember_token',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
My blade file register part (register.blade.php)
<body>
<form method="POST" role="form" action="//IJJI/resources/views/chat.blade.php">
<meta name="csrf-token" content="{{ csrf_token() }}">
<input id="name" name="name"type="text" class="form-control" placeholder="Entrez ici votre Pseudo *" value="" />
<label class="radio inline">
<input id="homme" type="radio" name="sexe" value="homme" checked>
<span> Homme </span>
</label>
<label class="radio inline">
<input id="femme" type="radio" name="sexe" value="femme">
<span>Femme </span>
</label>
<input id="age" name="age" type="integer" class="form-control" placeholder="Saisissez votre age *" value="" />
<input id="Email" name="email" type="email" class="form-control" placeholder="Saisissez votre Email *" value="" />
<input id="password" name="password" type="password" class="form-control" placeholder="Entrez votre Mot de Passe *" value="" />
<input id="confirmpassword" name="confirmpassword" type="password" class="form-control" placeholder="Confrimez votre Mot de Passe *" value="" />
<button type="submit" class="btnRegister">
Je deviens membre Gratuitement
</button>
</form>
</body>
I have done PHP artisan make auth generated the files, made .env file adequate to my MySQL database with the username and password, even checked the PhpMyAdmin configuration, but all in vain.
After 4 days of search in Google websites I can't figure out where I am wrong.
P.S : Another thing that could be wrong is that code like this :
#section
#endsection
never gets accepted and just shows like normal text on my browser.
Thanks a lot for your help
Check your laravel logs location: storage/logs you will get errors.
i have notice you are using $table->boolean('sexe') and in validation you are giving string boolen should be 0/1
'sexe'=> 'required:in:true,false',
also change in your html form to 0,1 currently you are using male, female
Are you getting error?
Besides, can you please the following line at the top of your form to see if there is any validation error or not. After that try submitting the form and see if there is any error or not!
#if(count($errors) > 0)
<div style="color:red">
#foreach ($errors->all() as $message)
<ul>
<li>{{$message}}</li>
</ul>
#endforeach
</div>
#endif
And remove the action form the form tags.
Use:
#csrf
or
{{csrf_field()}}
instead of
<meta name="csrf-token" content="{{ csrf_token() }}">
I have login form with two text fields email, password.when I tried to login with credentails it's working fine but when clear cache and then tried to login it gives the 'MethodNotAllowedHttp' exception.I am not getting the issue why it's showing this error. My code is as follows:
Route::post('users/login/5', 'administrator\usersController#login')->name('sl');
usersController.php
namespace App\Http\Controllers\administrator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Validator;
use Session;
class FreeusersController extends Controller {
function login(Request $request) {
$type = $request->segment(3);
//print_r($request);
echo "type=".$type;
echo $request->input('email');
echo $request->input('password');
die("sss");
if ($request->isMethod('post') && !empty($type)) {
$this->validate($request, [
'email' => 'required|min:5,max:50',
'password' => 'required|min:5,max:50'
]);
switch ($type) {
case 5:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '5', 'role' => 'father'];
break;
case 4:
$condArr = ['email' => $request->input('email'), 'password' => $request->input('password'), 'type' => '4', 'status' => true];
break;
}
if (Auth::attempt($condArr)) {
return redirect('administrator/dashboard');
} else {
return redirect(url()->previous())->withErrors(['password' => 'Invalid credentials'])->withInput();
}
} else {
return redirect("/");
}
}
}
<form action="/users/login/5" id="login-form" method="post" class="smart-form client-form">
{{ csrf_field() }}
<fieldset>
<section>
<label class="label">Email</label>
<label class="input"> <i class="icon-append fa fa-user"></i>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
</section>
<section>
<label class="label">Password</label>
<label class="input"> <i class="icon-append fa fa-lock"></i>
<input id="password" type="password" class="form-control" name="password">
</section>
</fieldset>
<footer>
<button type="submit" class="btn btn-primary">
LogIn
</button>
</footer>
</form>
You have to clear routes:
php artisan route:cache
Then it will remember that login action is post.
I think you are getting this error because you when you are calling this url there is another url with something like users/{id} which means anything after users/. May be you are using resource route. So, when you call url users/login/5 its taking login/5 as $id of that users/{id} url.
But that url is for GET method. You are calling this with post method, as a result you are getting this error.
Solution
You can try calling your url using route method like:
action="{{route('sl', ['id'=>5])}}"
If it doesn't work then you can change your route to something else. For example:
Route::post('user/login/5', 'administrator\usersController#login')->name('sl');
Here you can use user instead of users because you already have a url with a users. Don't forget to change your action too.
First look at your routes with php artisan route:list.
Then are you sure of your request verb ? Look in your navigator console to look at your requests.
I would like to start by apologizing for the newbish question.
I'm in the process of making a simple CRUD controller on Laravel.
My create method is as follows:
public function create(Request $request)
{
$dummy = new Dummy();
$dummy->title = $request->title;
$dummy->content = $request->dummy_content;
$dummy->created_at = new \DateTime();
$dummy->updated_at = new \DateTime();
$dummy->save();
return redirect()
->route('index/view/', ['id' => $dummy->id])
->with('message', 'Dummy created successfully');
}
my view method:
public function view($id)
{
$dummy = Dummy::find($id);
return view('index/view', [
'dummy' => $dummy
]);
}
my corresponding routes:
Route::get('index/view/{id}', 'IndexController#view');
Route::post('index/create', 'IndexController#create');
and my form:
<form action="create" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="dummy_content" cols="80" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
When I submit my form I get the following exception:
InvalidArgumentException in UrlGenerator.php line 314:
Route [index/view/] not defined.
I've been stuck here for quite some time and I still can't figure out why I'm not generating my route properly.
What am I missing?
You are trying to call a route when instead you should call the controller. This will do the trick
return redirect()->action('IndexController#view', ['id' => $id])->with($stuff);
Also, i suggest you to define aliases to routes, so you could do something like
In your controller:
return Redirect::route('route_alias', ['id' => $id])->with($stuff);
In your routes:
Route::get('/index/view/{id}', [
'as' => 'route_alias',
'uses' => 'IndexController#view'
]);