Ajax use in laravel 5.3 - php

I am in a bit of I a fix. I am trying to submit a form using Ajax. Now when I do this without creating the laravel default auth scaffold it works fine, but if add the auth scaffold it fails. I have tried all I can but can't seem to get it to submit.
Here is my code:
controller to send mail --
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class MailController extends Controller
{
//
public function index(Request $request)
{
if ($request->ajax()) {
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'mymessage' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
} else {
// get input fields values
$data = [
'firstName' => $request->input('first_name'),
'lastName' => $request->input('last_name'),
'email' => $request->input('email'),
'mymessage' => $request->input('mymessage'),
];
Mail::send('emails.email', $data, function ($message) {
official email
$message->to('xxxxxxxxx#gmail.com', 'My Name')->subject('Information');
});
return response()->json([
'responseText' => 'Mail was sent!'], 200);
}
} else {
return View('fail')->render();
}
}
}
The Route files:
Route::get('/', function () {
return view('welcome');
});
Route::post('/mail', [
'as' => 'mail',
'uses' => 'MailController#index'
]);
Auth::routes();
Route::get('/home', 'HomeController#index');
Ajax code:
$(document).ready(function() {
var options = {
beforeSubmit: validate,
url: '/mail',
data: $(this).serialize(),
type: 'POST',
dataType: 'json',
clearForm: true,
success: great,
error: lost
};
$('#footer-form').ajaxForm(options);
});
function validate(formData, jgForm, options) {
for (var i = 0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for all fields');
return false;
}
}
}
function great(responseText, statusText, formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', true);
// show alert on success
$(".alert-success").prop("hidden", false);
// remove mail error information if displayed
$(".alert-info").prop("hidden", true);
// reset google recaptcha
grecaptcha.reset();
}
function lost(formData) {
// prevent multiple form submission
$('#mail_btn').prop('disabled', false);
$(".alert-info").prop("hidden", false);
}
My form code:
<div class="col-sm-6">
<div class="footer-content" id="myfooter">
{!! Form::open(['action' => 'MailController#index', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('mymessage', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('mymessage', null, ['class' => 'form-control', 'rows' => 8, 'cols' => 3, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('mymessage'))
{{ $errors->first('mymessage') }}
#endif
</div>
<div class="form-group has-feedback">
{!! app('captcha')->display() !!}
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}
{!! Form::close() !!}
<div class="alert alert-success" id="mail_alert" role="alert" hidden>
Mail Sent!
</div>
<div class="alert alert-info" id="mail_info" role="alert" hidden>
Mail Sending Error!
</div>
</div>
</div>
Error message:
Failed to load resource: the server responded with a status of 401 (Unauthorized)

The problem was that I was using mailgun sandbox account hence I was only able to send mail when I use the laravel app with the auth scaffold include with the auth scaffold the app would allow as mailgun sandbox account don't send any reponse.
Solution was to use regular gmail send it and it responded as expected and the mail went through.

Related

Trouble with Route in laravel collective and laravel 7.6

I'm new to laravel. When I try to generate a form, the problem occurred.
My route
Route::get('post/add', "Post1Controller#add");
Route::post('post/store', "Post1Controller#store");
My Post1Controller
function add()
{
return view('post/create');
}
function store(Request $request)
{
echo "Had file";}
My form
{!! Form::open(['url'=> 'post/store','method'=>'POST', 'files'=> true]) !!}
<div class="form-group">
{!! Form::file('image', ['class' => 'form-control'])!!}
</div>
<div class="form-group">
{!! Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Title in here'])!!}
</div>
<div class="form-group">
{!!form::textarea('content','',['class'=> 'form-control', 'placeholder'=> 'Text in here'])!!}
</div>
<div class="form-group">
{!! Form::submit('Add', ['name'=>'sm-add', 'class' => 'btn btn-danger'])!!}
</div>
{!! Form::close() !!}`enter code here`
My issue: The GET method is not supported for this route. Supported methods: POST. Thank you for your support.

Laravel html form not validating form input

I am trying to set up a contact form on a one page site using laravel, I can't seem to be able to get the form to validate the user input and show any errors that the form might have.
email.blade.php:
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('textarea', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('textarea', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('textarea'))
{{ $errors->first('textarea') }}
#endif
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default']) !!}
{!! Form::close() !!}
Route: web.php:
Route::get('/ensignhospital', [
'as' => 'home',
'uses' => 'HomeController#home'
]);
Route::group(['before' => 'guest'], function () {
/*
* CSRF Protection
*
* */
Route::group(['before' => 'csrf'], function () {
Route::post('/ensignhospital', [
'as' => 'mail',
'uses' => 'HomeController#postSendMail'
]);
});
});
controller to handle for request:
class HomeController extends Controller {
public function home(){
return View('welcome');
}
public function postSendMail(ContactFormRequest $request){
if($request->fails()){
return Redirect::route('')
->withErrors()
->withInput();
}else{
return View('passed');
}
}
}
The form request validator class:
class ContactFormRequest 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 [
//
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'message' => 'required'
];
}
}
Problem the form does not validate when I don't enter a valid input. I need the form to validate user input and remain at the form position on the web page.
please note:
I used a .htaccess file to get the site which is on my computer to display the site root as localhost/mylaravelproject rather than the usual localhost/mylaravelprojec/public that one will normally see on a fresh install of laravel.
From the documentation here: https://laravel.com/docs/5.3/validation#form-request-validation
So, how are the validation rules evaluated? All you need to do is type-hint
the request on your controller method. The incoming form request is validated
before the controller method is called, meaning you do not need to clutter
your controller with any validation logic.
Laravel will never actually remain on the form. It will instead redirect, validate and then redirect back, with the errors. You do not need the check in your code if($request->fails()).

Populating select options from db - laravel 5.2

I'm using Laravel Collective and Laravel 5.2... I'm kinda new at this, so please if someone can help, I would be grateful.
I want to populate data to my view,
this is my controller:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests\SaveProfileRequest;
use App\Http\Requests;
use App\Clas;
use App\Profile;
use App\Http\Controllers\Controller;
class ClassesController extends Controller
{
public function getIndex() {
return view('admin.classes.list', [
'classes' => Clas::get()
]);
}
public function postIndex(Request $request) {
$class = Clas::create([
'profile_id'=>
'name' => $request ->input('class-name'),
]);
if($class->id) {
return redirect()->back()->with('message', [
'type'=> 'success',
'message' => 'Успешно записан нов клас!'
]);
}
return redirect()->back()->with('message', [
'type'=> 'danger',
'message' => 'Класът не е записан!'
]);
}
}
and in my View I have this
<div class="panel-body">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('class-name','Клас:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::text('class-name', null,['class' => 'form-control', 'placeholder' => 'например: 8а' ]) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile-name','Избери профил:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::select('profile-name') !!}
</div>
</div>
<div align="center">
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
My question is how to pass the data? What should i write in the controller and in the view to connect them?
With regards to you comment.
This returns a list (array) to the view:
EDITED
public function getIndex() {
return view('admin.classes.list', [
//'classes' => Clas::get() //returns object, profile
'profiles' => Profile::lists('name', 'id'); //returns array
]);
}
To populate the select menu with lists of profile_id and name
NB: I changed profile-name to profile_id
<div class="form-group">
{!! Form::label('profile_id','Избери профил:', ['class' => 'control-label col-md-3']) !!}
<div class="col-md-6">
{!! Form::select('profile_id', $profiles) !!}
</div>
</div>
Then your postIndex:
public function postIndex(Request $request) {
$class = Clas::create([
'profile_id'=> $request->get('profile_id'),
'name' => $request ->input('class-name'),
]);
if($class->id) {
return redirect()->back()->with('message', [
'type'=> 'success',
'message' => 'Успешно записан нов клас!'
]);
}
return redirect()->back()->with('message', [
'type'=> 'danger',
'message' => 'Класът не е записан!'
]);
}
Take a look at https://laravel.com/docs/5.0/views#basic-usage
You can pass view variables by calling the function view( string $script, array $viewVariables )

Patch update Authenticated User in Laravel

I'm trying to edit/update profile information into my Users table.
My idea is for the authenticated user to be able to edit his own profile in the Users table.
During the registration, you are only required to fill out a couple specific items (username, name, lastname, email, password) but I've also added a couple extra columns to the User table (city, country, phone, twitter, facebook).
I have a profile user page (route= '/profile') where all the information is shown. Of course all columns that aren't required during the registration are not filled in:
I also have an edit page where the columns that need info added are editable:
Here is the code for this editprofile.blade.php (where I try to send out a PATCH method):
...
{!! Form::model($user, ['route' => 'user/' . $user , 'method' => 'PATCH']) !!}
<div class="form-group form-horizontal">
<div class="form-group">
{!! Form::label('username', 'Username:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->username}}<label>
</div>
</div>
<div class="form-group">
{!! Form::label('email', 'E-mail:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->email}}<label>
</div>
</div>
<div class="form-group">
{!! Form::label('name', 'Name:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
<label class="align-left">{{ $user->name}} {{ $user->lastname}}<p>
</div>
</div>
<br />
<div class="form-group">
{!! Form::label('city', 'City:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('city', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('country', 'Country:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('country', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('phone', 'Phone:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('phone', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('twitter', 'Twitter link:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('twitter', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('facebook', 'Facebook link:', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::Text('facebook', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
{!! Form::submit('Save Profile', ['class' => 'btn btn-primary']) !!}
</div>
</div>
</div>
</div>
{!! Form::close() !!}
...
I have this is my Http/routes.php:
# Profile
Route::get('/profile', 'PagesController#profile');
Route::get('/profile/edit', 'ProfileController#edit');
Route::bind('user', function($id) {
$user = App\User::find($id)->first();
});
Route::patch('user/{user}', 'ProfileController#update');
I have an Http/Requests/UpdateUserRequest.php to validate the request:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest extends Request {
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'city' => 'max:30',
'country' => 'max:30',
'phone' => 'max:30',
'twitter' => 'max:30',
'facebook' => 'max:30'
];
}
}
And my Http/Controllers/ProfileController.php with the update fuction:
<?php namespace App\Http\Controllers;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ProfileController extends Controller {
public function edit()
{
$user = Auth::user();
return view('pages.editprofile')->withUser($user);
}
public function update(UpdateUserRequest $request, User $user)
{
$user->fill($request->all());
$user->save();
return redirect()->view('pages.editprofile')->withUser($user);
}
}
At the moment it seems I can't even open my 'editprofile.blade.php' page anymore, unless I remove the 'route' & 'methode' from my form.
I keep getting this error:
Could anyone guide me on how I should exactly trigger the PATCH methode?
change your form opening tag to
{!! Form::model($user, ['route' => 'user/' . $user->id , 'method' => 'PATCH']) !!}
you forgot '->id'
UPDATE
Change you Route
from
Route::patch('user/{user}', 'ProfileController#update');
to
Route::patch('user/{user}', 'as' => 'profile.patch', 'ProfileController#update');
and your form opening tag to
{!! Form::model($user, ['route' => array('profile.patch', $user->id), 'method' => 'PATCH']) !!}
You need to change:
{!! Form::model($user, ['route' => 'user/' . $user , 'method' => 'PATCH']) !!}
into:
{!! Form::model($user, ['route' => 'user/' . $user->id , 'method' => 'PATCH']) !!}
At the moment you create URL in your form with User object converted to Json - that's why it doesn't work.

Laravel 4.2 does not save data to the database

I have a problem, i don't know where i'm messing up but Laravel does not save data to the database and it does not display any errors. Here is my code:
User.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
protected $fillable = array('first_name', 'last_name', 'username', 'email', 'password', 'password_temp', 'code', 'active');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Routes.php
Route::get('/', array(
'as' => 'home',
'uses' => 'PagesController#home'
));
//Unauthenticated group
Route::group(array('before'=>'guest' ), function(){
//CSRF authentication
Route::group(array('before' => 'csrf'), function(){
//create account (POST)
Route::post('/account/create', array(
'as' => 'account-create',
'uses' => 'AccountController#postCreate'
));
});
//create account GET
Route::get('/account/create', array(
'as' => 'account-create',
'uses' => 'AccountController#getCreate'
));
});
Account.php //Here is the Controller that i used to create accounts
class AccountController extends BaseController{
public function getCreate(){
return View::make('account.create');
}
public function postCreate(){
$validator = Validator::make(Input::all(),
array(
'first_name' => 'required',
'last_name' => 'required',
'username' => 'required|max:20|min:3|unique:users',
'email' => 'required|max:50|email|unique:users',
'password' => 'required|min:6',
'passsword-repeat' => 'required|same:password'
)
);
if($validator->passes()){
//activation code
$code = str_random(60);
$user = new User;
//create an account
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->code = $code;
$user->active = 0;
$user->save();
//send email of activation
return Redirect::to('home')
->with('global', 'Your account has been created! We have sent an email to activate your account');
}else{
return Redirect::to('account/create')
->withErrors($validator)
->withInput();
}
}
}
Here is the view i have used:
Create.blade.php
#extends('master')
#section('content')
<div class="panel panel-default">
<div class="panel-heading">Please Register</div>
<div class="panel-body">
<div class="col-md-4 col-md-offset-4">
{{ Form::open(array('route' => 'account-create', 'class' => 'form-horizontal', 'method' => 'post'))}}
<fieldset>
<div class="control-group">
{{ Form::label('first_name', 'First name', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::text('first_name', Input::old('first_name'), array('class' => 'form-control input-medium', 'placeholder' => 'Enter Your First Name') )}}
<p class="error">{{ $errors->first('first_name')}}</p>
</div>
</div>
<div class="control-group">
{{ Form::label('last_name', 'Last name', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::text('last_name', Input::old('last_name'), array('class' => 'form-control input-medium', 'placeholder' => 'Enter Your Last Name') )}}
<p class="error">{{ $errors->first('last_name')}}</p>
</div>
</div>
<div class="control-group">
{{ Form::label('username', 'Username', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::text('username',Input::old('username'), array('class' => 'form-control input-medium', 'placeholder' => 'Enter Your Username') )}}
<p class="error">{{ $errors->first('username')}}</p>
</div>
</div>
<div class="control-group">
{{ Form::label('email', 'Email', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::text('email', Input::old('email') , array('class' => 'form-control input-medium', 'placeholder' => 'Enter Your Email') )}}
<p class="error">{{ $errors->first('email')}}</p>
</div>
</div>
<!-- Password input-->
<div class="control-group">
{{ Form::label('password', 'Password', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::password('password', array('class' => 'form-control')) }}
<p class="error">{{ $errors->first('password')}}</p>
</div>
</div>
<div class="control-group">
{{ Form::label('password-repeat', 'Re-Enter Password', array('class' => 'control-label') )}}
<div class="controls">
{{ Form::password('password-repeat', array('class' => 'form-control')) }}
<p class="error">{{ $errors->first('password-repeat')}}</p>
</div>
</div>
<!-- Button -->
<div class="control-group">
<div class="controls">
{{Form::submit('Sign Up', ['class' => 'btn btn-large btn-primary', 'id'=> 'signup'])}}
</div>
</div>
</fieldset>
{{ Form::close() }}
</div>
</div>
</div>
#stop
It validates well but whenever i want to create a user and save data to the database nothing is happening and it returns back to the same login page with the data i tried to save without any error message . please help me if you can spot my mistake

Categories