Im trying to create login form and its controller but when i try to login it doesnt work can any one help me i'm very new in laravel.
here is my form
<form action="/login" method="post">
{{ csrf_field() }}
<div class="form-group has-feedback">
<input type="email" name="email" class="form-control" placeholder="Email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-7">
<div class="checkbox">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-5">
<button type="submit" class="btn btn-primary btn-raised btn-block ">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
and here is my route
Route::get('/login', 'loginController#create');
Route::post('/login', 'loginController#store');
and my loginController is
class loginController extends Controller
{
public function __construct(){
$this->middleware('guest', ['except' => 'destroy']);
}
public function create(){
return view('pages.admin.login');
}
public function store(){
if(! auth()->attempt(request(['email', 'password']))){
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
}
My user modal is
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname','oname','lname', 'email', 'phone','password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Please where i'm i doing wrong on these, when i entered email and password as my credential it just refresh and back to login page
auth()->attempt() requires an array, you're sending the return value of request() as a single argument, may that be it?
Your function should be like this with Request facade.
public function store(Request $request){
if(! auth()->attempt($request->only(['email', 'password']))){
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
Here is how your attempt function should be like:
if(Auth::attempt( ['email'=> $request['email'],'password' => $request['password'] ])
Add these on top of LoginController
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
and modify your store method
public function store(Request $request){
$email = $request->email;
$password = $request->password;
if (! Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication Failed...
return back()->withErrors([
'message' => 'Please check your credentials'
]);
}
return redirect('/home');
}
Also remove password from $hidden in your User Model.
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
Hope it's helpful.
You can use php artisan make:auth and laravel will produce everything needed for a login including the controller and then you can go into your resource and edit to make it look how you imagined.
This is what my login controller looks like after using php artisan make:auth
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Related
I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest 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<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.
I am new to laravel. I want to insert users data to database using registerController in laravel.
What I have tried is:
register.blade.php
#extends('adminlte::auth.auth-page', ['auth_type' => 'register'])
#php( $login_url = View::getSection('login_url') ?? config('adminlte.login_url', 'login') )
#php( $register_url = View::getSection('register_url') ?? config('adminlte.register_url', 'register') )
#if (config('adminlte.use_route_url', false))
#php( $login_url = $login_url ? route($login_url) : '' )
#php( $register_url = $register_url ? route($register_url) : '' )
#else
#php( $login_url = $login_url ? url($login_url) : '' )
#php( $register_url = $register_url ? url($register_url) : '' )
#endif
#section('auth_header', __('adminlte::adminlte.register_message'))
#section('auth_body')
<?php $res= DB::table('states')->orderBy('name','asc')->get();
?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="First Name *" name="first_name" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="Last Name *" name="last_name" value="" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="email" class="form-control" name="email" value="" placeholder="Email *" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control phoneMask" placeholder="Phone *" name="phone" value="" required>
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-offset-4 submit_btn">
{{-- Register button --}}
<button type="submit" class="btn btn-block {{ config('adminlte.classes_auth_btn', 'btn-flat btn-primary') }}">
<span class="fas fa-user-plus"></span>
{{ __('adminlte::adminlte.register') }}
</button>
</div>
</div>
</div>
</form>
#stop
#section('auth_footer')
<p class="my-0">
<a href="{{ route('login') }}">
{{ __('adminlte::adminlte.i_already_have_a_membership') }}
</a>
</p>
#stop
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Auth;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users']
//'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
/*protected function create(array $data)
{
/*return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
dd($data);
$user= User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'mobile' => $data['phone']
]);
// dd($data['password'], $user->password);
return $user;
}*/
public function registerUsers(Request $request)
{
$first_name=$request->input('first_name');
$last_name=$request->input('last_name');
$email=$request->input('email');
$phone=$request->input('phone');
dd($request);
DB::insert('insert into users(first_name,last_name,email,phone)values(?,?,?,?)',[$first_name,$last_name,$email,$phone]);
}
}
web.php
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/register_user', 'Auth\RegisterController#registerUsers')->name('register_user');
Model
class User extends Authenticatable implements AuditableContract
{
use HasApiTokens, Notifiable;
use SoftDeletes;
use Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $fillable = ['first_name', 'last_name','email','phone','device_token','password','approved','added_by','removed','removed_by','deleted_at'];
}
When I try to submit this form, it is not inserting data to database and is showing HTTP error 500 and couldn't handle request.
What my form looks like
How to fix and insert data to database.
Try to add the cross-fire request forgery to your form. Generally I get this error when I forget it.
Add it like that in your view:
<?php $res= DB::table('states')->orderBy('name','asc')->get(); ?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
Route
Route::post('/test', 'Auth\RegisterController#test')->name('test');
Auth\RegisterController
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
.
.
.
public function test ( Request $request){
$rules = array(
'first_name' => 'required', 'string', 'max:255',
// add validation rules here
);
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$user = new User();
$user->name = $request->input('first_name');
//copy above line and add remaining fields.
$user->save();
return redirect()->back()->with(array('message' => 'user added.'));
} else {
return redirect()->back()->withErrors($validator)->withInput();
}
}
follow these steps
make sure your request received by the desired route
make sure you have passed validation
then input data like this
DB::table('post')->insert([
DB::table('posts')->insert([
'name_name' => \request()->name,
'last_name' => \request()->last_name,
'email' => \request()->email,
'phone' => \request()->phone,
]);
in laravel 5 i try the PasswordController and the ResetsPasswords but always i have a route probleme
Route.php
Route::controllers(['uses' => 'Auth/PasswordController']);
Route::get('home/ResetsPasswords',array('as'=>'getEmail' ,'uses' => 'home/ResetsPasswords#getEmail') );
Route::post('home/ResetsPasswords',array('as'=>'postEmail' ,'uses' => 'home/ResetsPasswords#postEmail' ));
Route::get('home/ResetsPasswords/{token}',array('as' => 'getReset','uses' => 'home/ResetsPasswords#getReset' ) );
Route::post('home/ResetsPasswords/{token}', array( 'as' => 'postReset','uses' => 'home/ResetsPasswords#postReset'));
Route::get('home/ResetsPasswords',array('as'=>'getEmailSubject' ,'uses' => 'home/ResetsPasswords#getEmailSubject') );
Route::get('home/ResetsPasswords',array('as'=>'redirectPath' ,'uses' => 'home/ResetsPasswords#redirectPath') );
The PasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
}
the ResetsPasswords.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetsPasswords.php
<?php
//namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait ResetsPasswords
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function getEmail()
{
return view('auth.password');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case Password::INVALID_USER:
return redirect()->back()->withErrors(['email' => trans($response)]);
}
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* #return string
*/
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return \Illuminate\Http\Response
*/
public function getReset($token = null)
{
if (is_null($token)) {
throw new NotFoundHttpException;
}
return view('auth.reset')->with('token', $token);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postReset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath());
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
Auth::login($user);
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}
and for the views
first the emails/password.blade.php
<?php
Click here to reset your password: {{ url('password/reset/'.$token) }}
?>
the auth/password.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
the reset.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/reset">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and finally my login view
Mot de passe oublié?
so the error is
Call to undefined method Laravel\Routing\Route::controllers()
can you please help me :/ i try to change the route many time but always the same problem !!!!!!!
thank you
Implicit controllers are deprecated on Laravel 5. You need to remove this:
Route::controllers(['uses' => 'Auth/PasswordController']);
More info: https://laravel.com/docs/5.2/routing#route-model-binding
This is for laravel 5
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
This is for laravel 5.2
Route::group(['middleware' => ['web']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
});
I think you are using in routes.php
use Illuminate\Routing\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
if you use this then the error comes.
Call to undefined method Illuminate\Routing\Route::controllers()
to avoid this error use this
use Illuminate\Support\Facades\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Note:Dont need to import anything route
leave it as
The below one also works
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
How would I insert rows in multiple tables (default User table and Parents table) when registering a new User?
I know I need to edit Models, AuthController and view.
My User Model:
namespace Jcfk\Models\User;
class User extends Model implements AuthenticatableContract,
CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* #var string
*/
protected $primaryKey = 'user_id';
/**
* #var bool
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function parents() {
return $this->hasOne("app\Models\Parents");
}
/**
* Is the current user an admin
*
* #return bool
*/
public function isAdmin() {
return $this->role_id === Role::ADMIN;
}
public function isParents() {
return $this->role_id === Role::PARENT;
}
}
Parents Model:
namespace Jcfk\Models\Parents;
class Parents extends Model
{
protected $table = 'parent';
public $timestamps = false;
public $primaryKey = 'user_id';
protected $fillable = ['name', 'phone', 'address', 'city_id', 'region',
'postalcode'];
public function user() {
return $this->belongsTo("app\User");
}
}
The Auth Controller:
namespace Jcfk\Http\Controllers\Auth;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Routing\Registrar;
use Jcfk\Models\User;
use Jcfk\Models\Parents;
use Validator;
use Jcfk\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar) {
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data) {
return Validator::make($data, [
//'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:user',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
$user = new User($data);
$parents = new Parents($data);
$user->save();
$user->Parents()->save($parents);
}
}
The database fields of Parents are user_id, name, phone, address, ...
The database fields of User are user_id, email, password, ...
I need help with my register.blade.php file as well
<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/register') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" value="{{ old('user_id') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
Create a service or repository layer.
Create the repository:
<?php
namespace App\Models\Repositories\User;
use App\Models\Entites\User;
use App\Models\Entites\Parent;
class UserRepository implements UserInterface
{
public function create($input)
{
$user = new User($data);
$parents = new Parents($data);
$user->save();
$user->Parents()->save($parents);
return $user;
}
}
This implements an interface so we can map the interface to an implementation of it, so it can be injected:
<?php
namespace App\Models\Repositories\User;
interface UserInterface
{
public function create($input);
}
Create a service provider, so it can be injected:
<?php
namespace App\Models\Repositories\User;
use Illuminate\Support\ServiceProvider;
class UserRepositoryServiceProvider extends ServiceProvider
{
/**
* Registers the UserInterface with Laravels IoC Container
* #return void
*/
public function register()
{
$this->app->bind('App\Models\Repositories\User\UserInterface', 'App\Models\Repositories\User\UserRepository');
}
}
Add your provider to the config/app.php file:
'providers' => [
/*
* Laravel Framework Service Providers...
*/
/*
* Your providers
*/
App\Models\Repositories\User\UserRepositoryServiceProvider::class,
],
Now in your controller methods, you can do this:
use App\Models\Repositories\User\UserInterface;
protected function create(UserInterface $userRepository, array $data) {
$userRepository->create($data);
}
I'm a newbie to Laravel so I'm not yet familiar with the errors it's returning, I hope someone can help me with this.
So I created a simple app with registration form and a login form and the registered user can post whatever he/she wants but I'm getting this error
This is the form where the user can post:
#section('content')
<section class="header">
<ul>
<li></li>
<li>Back to Profile</li>
</ul>
</section>
<div class="newpost">
<h3>What new today?</h3><br>
<form action="{{URL::route('createPost')}}" method="post" autocomplete="off">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title..." required>
</div>
<div class="form-group">
<label for="content">Write Report</label>
<textarea class="form-control" name="content" id="content" placeholder="Write Here..." rows="10"></textarea>
</div>
<button type="submit" class="btn2">Publish</button>
</form>
</div>
#stop
This is the route:
Route::get('/Newpost', array(
'uses' => 'LoginUsersController#newPost',
'as' => 'newPost'
));
Route::post('/CreatePost/{id}', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
and the controller
public function createPost($id)
{
$users = User::findOrFail($id);
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}
and the User model where I'm guessing is causing the error.
<?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('email', 'password');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function Post()
{
return $this->hasMany('Post', 'user_id');
}
}
Can someone please explain to me why I'm getting this error? Thanks
This error is caused because findOrFail can't find anything. So it fails.
If your route depends on the users id. You actually have to pass it along when creating your form:
<form action="{{URL::route('createPost', Auth::id())}}" method="post" autocomplete="off">
(Auth::id() retrieves the id of the current logged in user)
However instead, I suggest that you remove the user id from the createPost route and work with the currently logged in user directly in the controller:
Route::post('/CreatePost', array(
'uses' => 'LoginUsersController#createPost',
'as' => 'createPost'
));
And then:
public function createPost()
{
$user = Auth::user();
$post = array(
'title' => Input::get('title'),
'content' => Input::get('content')
);
$posts = new Post($post);
$user->post()->save($post);
dd($post);
}