I want to validate input in POST method but the result message shows that Method is Not Allowed. Here's my code for create new user in database (UserController.php)
public function userRegister(Request $request)
{
$data['error']['state'] = false;
$rules = [
'name' => 'required',
'username' => 'required|unique:username',
'nip' => 'required|unique:nip',
'email' => 'required|unique:email',
'phone' => 'required',
'avatar' => 'required',
'password' => 'required',
'faculty_id' => 'required',
'building_id' => 'required',
'room_id' => 'required'
];
$message = [
'required' => 'Fill the required field.',
'username.unique' => 'Username already taken.',
'nip.unique' => 'Staff ID already taken.',
'email.unique' => 'Email already taken.',
];
$validator = $this->validate($request,$rules,$message);
if($validator->fails()){
$data['error']['state'] = true;
$data['error']['data'] = $validator->errors()->first();
}
else{
$data['user']['name'] = $request->input('user.name');
$data['user']['surname'] = $request->input('user.surname');
$data['user']['username'] = $request->input('user.username');
$data['user']['nip'] = $request->input('user.nip');
$data['user']['email'] = $request->input('user.email');
$data['user']['password'] = Hash::make($request->input('user.password'));
$data['user']['phone'] = $request->input('user.phone');
$data['user']['level'] = $request->input('user.role');
$data['user']['username_telegram'] = $request->input('user.username_telegram');
$data['user']['user_email_action'] = $request->input('user.user_email_action');
$data['user']['user_telegram_action'] = $request->input('user.user_telegram_action');
$data['user']['faculty_id'] = $request->input('user.faculty');
$data['user']['building_id'] = $request->input('user.building');
$data['user']['room_id'] = $request->input('user.room');
$data['user']['verified'] = 0;
if(!empty($request->input('user.avatar'))){
$data['user']['avatar'] = $request->input('user.username').'-'.$request->input('user.new_avatar');
}
else{
$data['user']['avatar'] = 'default.png';
}
$user_id = DB::table('register')->insertGetId($data['user'],'id');
}
return response()->json($data);
}
Here's the message:
Error Message
Do you know how to solve it? Thank you.
Your question doesn't show the routes of your application but you'll need to make sure your form is set to post
<form action="/my/url/path" method="post">
and your route is set to 'post'
E.g.
Route::post('/my/url/path', 'MyController#userRegister');
Please note that if you're not using Laravel Collective you'll need to make sure you include the CSRF token
<form method="POST" action="/my/url/path">
#csrf (laravel 5.6)
{{ csrf_field() }} (previous versions)
Related
My application gives employees of a company the ability to edit their data(example: address). Once they change any of it, a manager gets an e-mail with their new information. The problem is that an email is sent every time a employee clicks update. I need the application to compare the info in the database and only send an email if there's new information. What is good way to achieve this? I am sorry I forgot to mention, the email needs to contain only the new iformation. So isDirty() would not work for me.
public function editcredentials_action(Request $request)
{
$user = Auth::user();
$address = $user->address;
$this->validate($request, [
'password' => 'max:255',
'language' => 'integer',
'facebook_profile' => 'max:255',
'twitter_profile' => 'max:255',
'street' => 'max:255',
'house_number' => 'max:255',
'city' => 'max:255',
'zip_code' => 'max:255',
'country' => 'max:255',
]);
if (!empty($request->get('password')) && $request->get('password')) {
$user->password = bcrypt($request->get('password'));
}
$user->facebook_profile = $request->get('facebook_profile');
$user->twitter_profile = $request->get('twitter_profile');
$user->language_id = $request->get('language');
$user->save();
if (!$address) {
$address = new UserAddress();
$address->user_id = $user->id;
}
$address->street = $request->street;
$address->house_number = $request->house_number;
$address->city = $request->city;
$address->zip_code = $request->zip_code;
$address->country = $request->country;
$address->save();
$data = [
'email' => $user->email,
'facebook' => $user->facebook_profile,
'twitter' => $user->twitter_profile,
'name' => $user->name . ' ' . $user->lastname,
'address' => $address,
];
Mail::send('emails.user-update', $data, function ($message) use ($data) {
$message->from('no-reply#example.com', 'Profile change');
$message->to('profilechange#example.com');
$message->subject('Profile change: ' . $data['name']);
});
Session::flash('message', trans('app.global.saved'));
return back();
//return redirect()->route('profile.edit-credentials');
}
I don't think isDirty() will work here, but you can save user data in the beginning:
$params = ['language', 'facebook_profile', 'twitter_profile', 'name'];
$oldUserData = auth()->user()->only($paramsToCOmpare);
Then compare the data after using save() method:
if (count(array_diff($oldUserData, $user->only($paramsToCompare))) > 0) {
// Data was changed.
}
You can do the same for UserAddress model. For password just check if it was filled in the form (since you're not displaying it anyway):
if (!empty($request->password))
I have a registration form that I'm creating using the blade templating like so:
{{ Form::open(array('url'=>'registerUser', 'method'=>'POST', 'class'=>'loginForm SignUp')) }}
In routes.php, I have the following route:
Route::post('registerUser', 'UsersController#doRegister');
But when I submit the form, I get a MethodNotAllowedHttpException. Pretty much every other question I've found online about this was a case of the form having the GET method while the route had POST, but mine match, so I'm pretty confused.
Edit: Here's my full routes file:
Route::get('', 'UsersController#showLogin');
Route::get('login', 'UsersController#showLogin');
Route::post('doLogin', 'UsersController#doLogin');
Route::get('signUp', 'UsersController#showSignUp');
Route::post('authenticateCode', 'UsersController#authenticateCode');
Route::post('requestCode', 'UsersController#requestCode');
Route::get('showRegister', 'UsersController#showRegister');
Route::post('registerUser', 'UsersController#doRegister');
Route::get('dashboard', 'DashboardController#showDashboard');
Here's the controller function:
public function doRegister() {
$rules = array(
'fname' => 'required|alpha|min:2',
'lname' => 'required|alpha|min:2',
'email' => 'required|email|unique:users',
'phone' => 'required|alpha_num|min:7',
'company' => 'required|alpha_spaces|min:2',
'password' => 'required|alpha_num|between:6,12|confirmed', // these password rules need to be improved
'password_confirmation' => 'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()) {
$user = User::create(array(
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
'phone' => Input::get('phone'),
'company' => Input::get('company')
));
// Update the invite key that was passed to the register page
// with this new user's ID.
$key = InviteKey::find(Input::get('key'));
$key->user_id = $user->id;
$key->save();
return Redirect::to('login')->with('message', 'Thank you for registering!');
} else {
return Redirect::to('register')
->with('message', 'The following errors occurred')
->withErrors($validator)
->withInput(Input::except('password'));
}
}
I'm new to Laravel. I have a form with a File upload function on it. How can I validate their file? I will only allowed Microsoft Word files. Here's my validation code.
I just want check if they insert a ms word file and if not it will not be processed.
public function store()
{
// Validate
$rules = array(
'pda' => 'required|unique:forms',
'controlnum' => 'required|unique:forms',
'date' => 'required',
'churchname' => 'required',
'title' => 'required',
'pastorname' => 'required',
'contactnum' => 'required',
'address' => 'required',
'state' => 'required',
'region' => 'required',
'area' => 'required',
'city' => 'required',
'zipcode' => 'required|numeric|max:9999',
'tgjteachertraining' => 'required',
'localcontact' => 'required',
'tgjdatestart' => 'required',
'tgjdateend' => 'required',
'tgjcourse' => 'required|numeric',
'childrengraduated' => 'required|numeric|max:450',
'childrenacceptjesus' => 'required|numeric',
'howmanycomitted' => 'required|numeric',
'recievedbibles' => 'required|numeric',
'descgradevent' => 'required',
'whatwillyoudo' => 'required',
'pastortest' => 'required',
'teachertest' => 'required',
'childrentest' => 'required',
'file' => 'required|max:10000',
);
$validator = Validator::make(Input::all(), $rules);
// process the form
if ($validator->fails()) {
return Redirect::to('forms/create')->withErrors($validator);
} else {
// store
$forms = new Forms;
$forms->pda = Input::get('pda');
$forms->controlnum = Input::get('controlnum');
$forms->date = Input::get('date');
$forms->churchname = ucwords(Input::get('churchname'));
$forms->title = ucwords(Input::get('title'));
$forms->pastorname = ucwords(Input::get('pastorname'));
$forms->address = Input::get('address');
$forms->contactnum = Input::get('contactnum');
$forms->state = Input::get('state2');
$forms->region = Input::get('region2');
$forms->area = Input::get('area2');
$forms->citytown = Input::get('city2');
$forms->zipcode = Input::get('zipcode');
$forms->tgjteachertraining = Input::get('tgjteachertraining');
$forms->localcontact = ucwords(Input::get('localcontact'));
$forms->tgjdatestart = Input::get('tgjdatestart');
$forms->tgjdateend = Input::get('tgjdateend');
$forms->tgjcourse = Input::get('tgjcourse');
$forms->childrengraduated = Input::get('childrengraduated');
$forms->childrenacceptjesus = Input::get('childrenacceptjesus');
$forms->howmanycomitted = Input::get('howmanycomitted');
$forms->recievedbibles = Input::get('recievedbibles');
$forms->descgradevent = Input::get('descgradevent');
$forms->whatwillyoudo = Input::get('whatwillyoudo');
$forms->pastortest = Input::get('pastortest');
$forms->teachertest = Input::get('teachertest');
$forms->childrentest = Input::get('childrentest');
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$destinationPath = 'uploads/'.Input::get('pda');
$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
$forms->docurl = 'uploads/'.Input::get('pda').'/'.$filename;
if( $uploadSuccess ) {
$forms->save();
//Session::flash('message', 'Successfully submitted form!');
return Redirect::to('forms/create');
Session::flash('message', 'Successfully submitted form!');
}
else {
return Response::json('error', 400);
}
}
}
To validate mime type of a file input in Laravel you can use the mimes rule. Remember to match the mime type detected with the actual mime of file you provide. It may vary on different servers.
For example, you want to enable adding and word document in you form:
1) in config/mimes.php add the below mime types:
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
2) in your validation $rules add the following elements:
'file' => 'required|max:10000|mimes:doc,docx' //a required, max 10000kb, doc or docx file
Try this?
'file' => 'required|max:10000|mimes:application/vnd.openxmlformats-officedocument.wordprocessingml.document'
You may want to set some custom message for the response though :)
As of Laravel 9.22 you can write the validation rules a lot shorter and more readable like:
'file' => ['required', File::types(['doc', 'docx'])->smallerThan(10000)]
You can find the available methods in this pr: https://github.com/laravel/framework/pull/43271
So I have this form with these fields
{{ Form::open(array('url' => 'user', 'id' => 'user_create_form')) }}
<div class="form-input-element">
<label for="facebook_id">ID Facebook</label>
{{ Form::text('facebook_id', Input::old('facebook_id'), array('placeholder' => 'ID Facebook')) }}
</div>
<div class="form-input-element">
<label for="twitter_id">ID Twitter</label>
{{ Form::text('twitter_id', Input::old('twitter_id'), array('placeholder' => 'ID Twitter')) }}
</div>
<div class="form-input-element">
<label for="instagram_id">ID Instagram</label>
{{ Form::text('instagram_id', Input::old('instagram_id'), array('placeholder' => 'ID Instagram')) }}
</div>
{{ Form::close() }}
I'd like to tell Laravel that at least one of these fields is required. How do I do that using the Validator?
$rules = array(
'facebook_id' => 'required',
'twitter_id' => 'required',
'instagram_id' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
Try checking out required_without_all:foo,bar,..., it looks like that should do it for you. To quote their documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Example:
$rules = array(
'facebook_id' => 'required_without_all:twitter_id,instagram_id',
'twitter_id' => 'required_without_all:facebook_id,instagram_id',
'instagram_id' => 'required_without_all:facebook_id,twitter_id',
);
$validator = Validator::make(Input::all(), $rules);
**For automatic validation**
$rules = array(
'facebook_id' => 'required_without_all:twitter_id,instagram_id',
'twitter_id' => 'required_without_all:facebook_id,instagram_id',
'instagram_id' => 'required_without_all:facebook_id,twitter_id',
);
$message = array(
'facebook_id' => 'The facebook field is required when none of twitter / instagram are present.',
'twitter_id' => 'The twitter field is required when none of facebook / instagram are present.',
'instagram_id' => 'The instagram field is required when none of twitter / facebook are present.');
$validator = Validator::make(Input::all(), $rules, $message)->validate();
use this code i already made it
php artisan make:rule RequiredWithout
use Illuminate\Contracts\Validation\Rule;
class RequiredWithout implements Rule
{
private $without = [];
private $current_attribute = "";
private $no_need = "";
public function __construct($without)
{
if(is_string($without))
{
$this->without = [$without];
}
elseif(is_array($without))
{
$this->without = $without;
}
else
throw new \Exception('$without must be array or string');
}
public function passes($attribute, $value)
{
$this->current_attribute = $attribute;
$requests = request()->all();
foreach ($this->without as $WO_i)
{
if(array_key_exists($WO_i, $requests))
{
$this->no_need = $WO_i;
return false;
}
}
return true;
}
public function message()
{
return "the $this->current_attribute Field and $this->no_need Shouldn't be Exist in this request together";
}
}
and then in the controller use this
'country_id' => ['nullable', 'exists:countries,id', new ValidCountryID(), new RequiredWithout('country_code')],
'country_code' => ['nullable', 'exists:countries,IsoCountryCode', new ValidCountryID(), new RequiredWithout('country_id')],
Rule required_without_all can be hacked to get the desired results.
Create a dummy rule for require_one, and pass all fields to the rule params. if none exists, the dummy rules fires up with required.
$rules = array(
'facebook_id' => 'required',
'twitter_id' => 'required',
'instagram_id' => 'required',
);
$keys = implode(',', array_keys($rules));
$rules['require_one'] = "required_without_all:$keys";
$messages = [
'require_one.required_without_all' => '*At least one field is required'
];
$validator = Validator::make(Input::all(), $rules, $messages);
This is possible to implement with an After Validation Hook:
$validator->after(function ($validator) {
if (empty($this->validated())) {
$validator->errors()->add('empty', 'At least one field must be provided.');
}
});
Or if you are using a FormRequest:
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->validated())) {
$validator->errors()->add('empty', 'At least one field must be provided.');
}
});
}
I am trying to set up a queued email in Laravel 4 using the Iron.io driver. I would like to pass some details to the email's Subject and From attributes but they seem to not be making it into the queue request and their presence causes the email to not be sent (not sure where to look for a log with errors). However, simply using Mail::Send() works fine.
Here is the code in question:
public function handleFeedbackForm()
{
$data = array(
'name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'),
'commentType' => Input::get('commentType'),
'testimonialPublish_answer' => Input::get('testimonialPublish_answer'),
'comment' => Input::get('message')
);
$rules = array(
'name_f' => 'required',
'name_l' => 'required',
'email' => 'required|email',
'message' => 'required'
);
$v = Validator::make(Input::all(), $rules);
if ($v->passes())
{
$emailInfo = array('name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'));
Mail::queue('emails.feedback', $data, function($message) use($emailInfo)
{
$recipients = array();
$form = MailType::find(1);
foreach ($form->users as $user)
{
$recipients[] = $user->email;
}
if (count($recipients) == 0)
{
// Nobody for this field, send to webmaster
$recipients[] = 'someone#somewhere.com';
}
$message->to($recipients)
->from($emailInfo['email'])
->subject('Foobar Feedback Form Message - ' . $emailInfo['name_f'] . ' ' . $emailInfo['name_l']);
});
return Redirect::to('contact')->with('feedbackSuccess', true);
}
else
{
return Redirect::to('contact')->with('feedbackError', true);
}
}
Any ideas? Thanks!