I am trying to pull list of data from database and show it as a dropdown in a registration form. But I get error undefined variable universities.
Register Controller
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'university' => $data['university'],
'school_dept' => $data['school_dept'],
])
->with(compact('universities','sch_depts'));
}
register.blade.php
<div class="form-group{{ $errors->has('university') ? ' has-error' : '' }}">
<label for="university" class="col-md-4 control-label">University</label>
<div class="col-md-6">
{!! Form::select('university', $universities, null, array('id' => 'universitiy', 'class' => 'form-control')) !!}
#if ($errors->has('university'))
<span class="help-block">
<strong>{{ $errors->first('university') }}</strong>
</span>
#endif
</div>
</div>
I am getting an error universities undefined.
Let's assume you have a controller called RegisterController, the create method should only return view and it's corresponding data.
public function create()
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return view('register', compact('universities', 'sch_depts'));
}
and you should also have a store method:
public function store(\Illuminate\Http\Request $request)
{
// your validation goes here
// or just use form request validation
// docs: https://laravel.com/docs/5.4/validation#form-request-validation
User::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password')),
'university' => $request->get('university'),
'school_dept' => $request->get('school_dept'),
]);
// login user here or redirect to success page
}
and your routes/web.php file should contain the following routes:
Route::get('register', 'RegisterController#create');
Route::post('register', 'RegisterController#store');
This is really basics of Laravel, please read the docs.
P.S. Laravel comes with great Authentication system, which you can override to your needs.
This is what I did in Laravel 7, I'm also using the default authentication implementation from Laravel, so it might help
The solution is: in the RegisterController overwrite the method showRegistrationForm (which is declared in /vendor/laravel/ui/auth-backend/RegisterUsers) and add the data array.
So you will add something like this to your RegisterController
public function showRegistrationForm()
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return view(
'auth.register',
[
'universities' => $universities,
'sch_depts' => $sch_depts
]
);
}}
Related
I want to save some form data, and I'm Getting error.
The Error
Action App\Http\Controllers\Admin\ConcursoController#store not defined. (0)
My Form
{!! Form::open(['action'=>'Admin\ConcursoController#store', 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('company','Entidade')}}
{{Form::text('company','',['class' => 'form-control', 'placeholder' => 'Nome da entidade aquĆ..'])}}
</div>
{{Form::submit('submeter', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
My Route
$this->group(['middleware' => ['auth:admin'], 'namespace' => 'Admin', 'prefix' => 'admin'], function(){
$this->get('/', 'AdminController#index')->name('admin.home');
$this->resource('concursos', 'ConcursoController');
});
Controller index Method
public function index()
{
$concursos = Concurso::all();
$title = 'Concursos';
return view('admin.concursos.index',compact('title'))->with('concursos',$concursos);
}
Controller Create method
public function create()
{
return view('admin.concursos.create');
}
Controller Store Method
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
]);
//Criar concurso
$concurso = new Concurso;
$concurso->title = $request->input('title');
$concurso->body = $request->input('body');
$concurso->save();
return redirect('/admin/concursos')->with('Success', 'Concurso Adicionado');
}
Laravel version 5.7.14
Probably check this file: App\Http\Controllers\Admin\ConcursoController and see if you have a function/method called 'store'. The error is pretty straightforward that script can't find that function.
replace your form
['route' => ['concursos.store']
like
{!! Form::model($transactions, ['route' => ['transaction.store'], 'method' => 'POST','class'=>"form-horizontal"]) !!}
Welcome ! I have a problem I try to use this https://github.com/cmgmyr/laravel-messenger Laravel package for private messaging on Laravel 5.2. When i didn't have any recipients I could post a message but when I add new user to database and recipients showed in form now I have an error : trying to get property of non -object. All controllers and views are copied from examples from link above.
Regards
Message controller :
<?php
namespace App\Http\Controllers;
use App\User;
use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Participant;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
class MessagesController extends Controller
{
/**
* Show all of the message threads to the user.
*
* #return mixed
*/
public function index()
{
$currentUserId = Auth::user()->id;
// All threads, ignore deleted/archived participants
$threads = Thread::getAllLatest()->get();
// All threads that user is participating in
// $threads = Thread::forUser($currentUserId)->latest('updated_at')->get();
// All threads that user is participating in, with new messages
// $threads = Thread::forUserWithNewMessages($currentUserId)->latest('updated_at')->get();
return view('messenger.index', compact('threads', 'currentUserId'));
}
/**
* Shows a message thread.
*
* #param $id
* #return mixed
*/
public function show($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('messages');
}
// show current user in list if not a current participant
// $users = User::whereNotIn('id', $thread->participantsUserIds())->get();
// don't show the current user in list
$userId = Auth::user()->id;
$users = User::whereNotIn('id', $thread->participantsUserIds($userId))->get();
$thread->markAsRead($userId);
return view('messenger.show', compact('thread', 'users'));
}
/**
* Creates a new message thread.
*
* #return mixed
*/
public function create()
{
$users = User::where('id', '!=', Auth::id())->get();
return view('messenger.create', compact('users'));
}
/**
* Stores a new message thread.
*
* #return mixed
*/
public function store()
{
$input = Input::all();
$thread = Thread::create(
[
'subject' => $input['subject'],
]
);
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'body' => $input['message'],
]
);
// Sender
Participant::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'last_read' => new Carbon,
]
);
// Recipients
if (Input::has('recipients')) {
$thread->addParticipant($input['recipients']);
}
return redirect('messages');
}
/**
* Adds a new message to a current thread.
*
* #param $id
* #return mixed
*/
public function update($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('messages');
}
$thread->activateAllParticipants();
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::id(),
'body' => Input::get('message'),
]
);
// Add replier as a participant
$participant = Participant::firstOrCreate(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
]
);
$participant->last_read = new Carbon;
$participant->save();
// Recipients
if (Input::has('recipients')) {
$thread->addParticipant(Input::get('recipients'));
}
return redirect('messages/' . $id);
}
}
Standard routes:
Route::group(['prefix' => 'messages'], function () {
Route::get('/', ['as' => 'messages', 'uses' => 'MessagesController#index']);
Route::get('/create', ['as' => 'messenger.create', 'uses' => 'MessagesController#create']);
Route::post('/', ['as' => 'messages.store', 'uses' => 'MessagesController#store']);
Route::get('{id}', ['as' => 'messages.show', 'uses' => 'MessagesController#show']);
Route::put('{id}', ['as' => 'messages.update', 'uses' => 'MessagesController#update']);
});
And standard view:
{!! Form::open(['route' => 'messages.store']) !!}
<div class="col-md-6">
<!-- Subject Form Input -->
<div class="form-group">
{!! Form::label('subject', 'Subject', ['class' => 'control-label']) !!}
{!! Form::text('subject', null, ['class' => 'form-control']) !!}
</div>
<!-- Message Form Input -->
<div class="form-group">
{!! Form::label('message', 'Message', ['class' => 'control-label']) !!}
{!! Form::textarea('message', null, ['class' => 'form-control']) !!}
</div>
#if($users->count() > 0)
<div class="checkbox">
#foreach($users as $user)
<label title="{{ $user->name }}"><input type="checkbox" name="recipients[]" value="{{ $user->id }}">{!!$user->name!!}</label>
#endforeach
</div>
#endif
<!-- Submit Form Input -->
<div class="form-group">
{!! Form::submit('Submit', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
</div>
I am a beginner with php and laravel. I have recently created a form at the bottom of my website, that when you click the submit button it sends the data to an email address.
However if you don't fill it in correctly and click submit it refreshes the page and returns to the top of the page. If you submit the form correctly it goes to /contact.
What I am desperate to do is keep the page at the same point on the website (with the form on the screen) instead of refreshing the screen. Same if the form is submitted correctly I would like the screen to stay still.
Routes/web.php:
Route::get('/', 'PagesController#home');
Route::get('about', 'PagesController#about');
Route::get('contact',
['as' => 'contact', 'uses' => 'AboutController#create']);
Route::post('contact',
['as' => 'contact_store', 'uses' => 'AboutController#store']);
ContactFormRequest.php:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
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 [
'name' => 'required',
'email' => 'required|email',
'number' => 'required',
'message' => 'required',
];
}
}
AboutController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
class AboutController extends Controller
{
public function create()
{
return view('pages.contact');
}
public function store(ContactFormRequest $request)
{
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
}
contact.blade.php
<div class="one-half">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!}
<div class="form-group">
{!! Form::text('name', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your name')) !!}
</div>
<div class="form-group">
{!! Form::text('email', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your e-mail address')) !!}
</div>
<div class="form-group">
{!! Form::number('number', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your Number')) !!}
</div>
<div class="form-group">
{!! Form::text('message', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your message')) !!}
</div>
<div class="form-group">
{!! Form::submit('Contact Us!',
array('class'=>'form-button btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
I am also new to using stackoverflow, so I apologise ahead if I have missed anything or done anything incorrectly. Please let me know if you need anything more.
Can't really understand your problem, but try to add this in your store() method:
return \Redirect::back()->with('message', 'Thanks for contacting us!');
But it looks like you want to submit/validate your forms without refreshing the page, so the only solution for this is to use AJAX requests.
May be this can be something. Using the validation helper.
function store(ContactFormRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'number' => 'required',
'message' => 'required',
]);
// If !$this->validate Laravel will automatic return to the previous page (the form page)
// And you can grab the errors with $errors->first('name'), $errors->first('email') etc
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
Grab the errors like this:
#if ($errors->has('message'))
<span class="help-block">
<strong>{{ $errors->first('message') }}</strong>
</span>
#endif
Here you the docs about the validation, if you are using Laravel 5.3
This question already has answers here:
Validation error in Laravel - $errors array does not get populated after the validation failure
(3 answers)
Closed 6 years ago.
I'm trying to validate a login/signup system in Laravel 5.2.
I'm using welcome.blade.php as the index page which contains two forms for both signup and signin
This is how my UserController.php is set up:
namespace authme\Http\Controllers;
use Illuminate\Http\Request;
use authme\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function getDashboard()
{
return view('dashboard');
}
public function doSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users',
'first_name' => 'required|max:120',
'password' => 'required|min:6'
]);
$email = $request['email'];
$password = bcrypt($request['password']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$location = $request['location'];
$phone = $request['phone'];
$user = new User();
$user->email = $email;
$user->password = $password;
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->location = $location;
$user->phone = $phone;
$user->save();
Auth::login($user);
return redirect()->route('dashboard');
}
public function doSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
To show the errors during signup/login, in my view file (welcome.blade.php), I've included:
#if(count($errors) > 0)
<div class="row">
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
and the routes are set up like this:
Route::group(['middleware' => ['web']], function() {
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#doSignUp',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController#doSignIn',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard'
]);
});
The forms are working fine when entering correct details. However when I enter incorrect data:
When I try to submit the blank form, it just redirects back to the original page, but no errors are shown
When I try to enter an email that is already in use, it again redirects back to the original page, but no errors are displayed
However, I couldn't find any possible syntax error in my code. Is there any logical errors?
PS:
I've not edited or modified App\Exceptions\Handler
None of the answers to questions asked both here and here solves my problem
If you're using Laravel version higher or equal to 5.2.25 you no longer need to put your routes in the web middleware. It is now automatically applied.
Putting your routes in the web middleware in the routes.php actually causes the problem.
Explained here.
You can also use following codes to show the errors for sign in with invalid credential.
public function doSignIn(Request $request)
{
$rules = array(
'email' => 'required',
'password' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()){
return redirect('welcome')
->withErrors($validator)
->withInput();
}else{
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
}
}
It seems to me your validation error messages are not getting saved to the session. Have a look at this.
https://github.com/laravel/framework/issues/12022
I'm trying to do a basic authentication and when I try to authenticate the user,but Auth :: attempt method returns false
Blade
{{ Form::open(array('url' => 'usuario')) }}
<input type="text" class="text" id="email" name="email" placeholder="Correo" {{(Input::old('email')) ? 'value ="'. Input::old('email').'"' : '' }}>
<p>{{ $errors->first('email') }}</p>
<input type="text" class="text" id="password" name="password" placeholder="ContraseƱa" >
<p>{{ $errors->first('password') }}</p>
{{ Form::submit('Ingresar', array('class' => 'bg1')) }}
{{ Form::close() }}
Controller
class UsuarioController extends BaseController{
public function doLogin(){
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('usuario')->withErrors($validator)->withInput(Input::except('password'));
}else{
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if(Auth::attempt($userdata)){
return View::make('hello');
}else{
return Redirect::to('usuario');
}
}
}
}
Auth
'driver' => 'database',
'model' => 'Usuario',
'table' => 'Usuario',
Model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Usuario extends Eloquent implements UserInterface, RemindableInterface{
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $hidden = array('Contrasena');
protected $fillable = array(
'Nombre',
'Apellido',
'Tipo',
'password',
'email',
'Fono',
'Foto'
);
}
The code always returns false and redirects me to login, use incorrect data when the database
There are many reasons that can make it return false every time:
1) Your password is not correctly stored/hashed, you must hash it with:
Hash::make($password);
This is a way to create users and store passwords correctly hashed by Laravel:
$user = new User;
$user->email = 'example#domain.com';
$user->password = Hash::make('thePasswordToBeHashed');
$user->save();
2) Your password column size has not enough room to store a hashed password. It must be at least 60 bytes long, but migrating it with:
$table->string('password');
Is a good practice, because if this size somehow changes in the future you won't have problem.
3) You don't have a user with the e-mail (Correo) you are trying to login. Double check it, because this is more frequent than we think. And you can also try to do it manually to see if it really works:
$userdata = array(
'Correo' => 'youremail#domain.com',
'Password' => 'password'
);
dd( Auth::attempt($userdata) );
4) Data is not being correctly passed by your form, check if your form really works, by dying it with:
dd(Input::all());
And check if you get the correct data.
5) You have a validation, so the problem could be on it. Add another die message to be sure:
if($validator->fails())
{
dd('Validation is failing!');
...
}
6) From the comment:
$userData = array('email' => Input::get('email'), 'password' => Input::get('password'));
return (string) Auth::attempt($userData));
7) Try to create a different user manually:
$user = new User;
$user->email = 'example#domain.com';
$user->password = Hash::make('passwordExample');
$user->save();
And login with it:
$userData = array('email' => 'example#domain.com', 'password' => 'passwordExample');
return (string) Auth::attempt($userData));