laravel 4 redirection issue - laravel

I have a registration form and it was working until it just didn't. I am sure I did something with the code because I am new to laravel 4 so I am unable to identify my wrong doing. Now I am getting
This webpage has a redirect loop.
This is the route file:
Route::get('/','MainController#index');
Route::get('/login', 'MembersController#login');
Route::get('/signup', 'MembersController#signup');
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');
/* Handle authenticating a user when loggin in*/
Route::post('register', array(
'uses' => 'MembersController#register',
'as' => 'members.register'
));
and this is the form opening:
#section('content')
{{ Form::open(array('route' => 'members.register')) }}
......
{{ Form::close() }}
#stop
and this is the validation where if there is an error, it used to redirect to the sign-up page again and show them (and it did until it broke)
public function register()
{
$rules = array(
# place-holder for validation rules
'firstname' => 'Required|Min:3|Max:40|Alpha',
'lastname' => 'Required|Min:3|Max:40|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'country' => 'Required',
'password' =>'Required|AlphaNum|Between:7,15|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:7,15'
);
/*Create new user if no user with entered email exists. Use validator to ensure all fields are completed*/
$user = new User;
$validator = $this->validate(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('register')->withErrors($validator);
}else{
echo "Success";
}
}
Thanks for the help :)

Change the following line
return Redirect::to('register')->withErrors($validator);
with this
return Redirect::back()->withInput()->withErrors($validator);
You are calling the route register infinite times.
Remove this route as well. You only need post route.
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');

Related

Laravel authentication check returns false after log in

I'm trying to register a user in my application and log him in automatically after successfully registering.
What i'm doing:
Sending an HTTP request from the front-end using axios:
register() {
this.loading = true
axios.post('/api/v1/list/register', {
email: this.data.email,
password: this.data.password
}).then((re) => {
this.loading = false
})
}
Back-end controller:
public function register() {
$data = request()->validate([
'email' => ['required', 'string', 'email', 'unique:users'],
'password' => ['required', 'string', 'min:7',],
]);
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Auth::login( $user );
return response()->json([
'user' => Auth::user(),
]);
}
The user get's registered successfully and the server returns the user just fine, although when i refresh the page Auth::check() returns false as a result to display the register page again
<list-property :auth="{{ json_encode(Auth::check()) }}"></list-property>
#if(!Auth::check())
<login-dialog></login-dialog>
#endif
Routes web.php file
Route::get('/list-property', [App\Http\Controllers\MainController::class, 'listProperty']);
I used FILESYSTEM_DRIVER file and database, both had the same issue, what could be the problem?
For anyone who might be experiencing the same issue, the registration was happening through an API route which is incorrect, API routes are stateless, i moved the registration method inside web.php and it worked just fine.

Laravel route always not defined although it is declared

I tried adding a position to my user and setting it on users_positions table.
I created a new query alongside with the auth user create. When re-routing it to the root URL, it always comes back as
InvalidArgumentException
Route [/] not defined.
Controller
protected function create(array $data)
{
$id = User::create([
'firstname' => $data['firstname'],
'middlename' => $data['middlename'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
]);
DB::table('users_positions')->insert([
[
'user_id' => $id->id,
'position_desc' => $data['position'],
'primary' => "1",
]
]);
return redirect()->route('/')
->with('success', 'Successfully added a user account');
}
Route
Auth::routes();
Route::get('/home', 'HomeController#index')->name('name');
Route::get('/', function () {
return view('incident-reports.index');
})->middleware('auth');
The query is successful but the route still not defined.
When I try manually going to the root URL http://127.0.0.1:8000. It will work.
My plan is after adding user and the user_position it will come back at root URL and prompting an alert if it is success or error.
if you want to redirect with the path, send it as parameter to redirect() method
return redirect('/');
the route() method is to redirect to a route by Alias
route
Route::get('/', function () {
return view('incident-reports.index');
})->middleware('auth')->alias('root');
redirect
return redirect()->route('root');
Change this line:
return redirect()->route('/')
->with('success', 'Successfully added a user account');
to this
return redirect()->to('/')
->with('success', 'Successfully added a user account');
route() expects a route name as argument. '/' is a url

Laravel 5.7 Multi Authentication

I created another authentication as Admin in Laravel 5.7 Additionally to its default authentication. They both function correctly but, the new authentication that I have created does no show error messages
For fault login attempts as default authentication does.
here the code I used for LoginController created for Admin model.
public function showLoginForm(){
return view('admin.login');
}
//Validate the form data
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|string',
]);
//Attempt to lo the Admin in
$credential = [
'email' => $request->email,
'password' => $request->password,
];
//Attempt to log the Admin in
if(Auth::guard('admin')->attempt($credential, $request->member)){
return redirect()->intended(route('admin.home'));
}
//If unscuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email','remember'));
}
Please tell me how to fix this. Thanks.
you need to validate those data
// taken from the default auth controller
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
and in the blade file show the errors
such as
to diaplay all the errors
#if ($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
#endif
and to display the specific errors
<input type="text" name="firstname">
#if ($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
#endif
if you are not clear about that just watch the tutorial at
https://pusher.com/tutorials/multiple-authentication-guards-laravel

Controller didn't get more arguments laravel

I'm trying to send two arguments and one request to controller with post request. This is the code where I send the arguments:
<form class="form-horizontal" name="form1" method="post" action="{{ route('shipment_view', $uniqueid, $category_name) }}" role="form" enctype="multipart/form-data">
And this is the controller where I'm sending the arguments:
public function storeShipment(Request $request, $number, $category_name){
$category = Category::where('category_name', $category_name)->first();
$user = Auth::user();
$item = new Item([
'id' => $user->id,
'category_id' => $category->id,
'unq' => $number,
'fullname' => $request->input('name'),
]);
$item->save();
}
But when I open the view it gives me error
ErrorException in NewShipmentController.php line 53:
Missing argument 3 for App\Http\Controllers\NewShipmentController::storeShipment()
Update:
My route function:
Route::post('/ship/preview/{number}',[
'uses' => 'Controllerr#storeShipment',
'as' => 'shipment_view'
]);
Any ideas?
replace your route function with the below one
Route::post('/ship/preview/{number}/{category_name}',[
'uses' => 'Controllerr#storeShipment',
'as' => 'shipment_view'
]);
Hope this solves your problem.
You can get the all the parameters through request it self But before this how you are defining the route
public function storeShipment(Request $request){
$number = $request->number;
$category_name = $request->number
}

Laravel 4 route protected pages

I have a controller UserController.php which contains the following methods:
getIndex(), getAll(), getCreate(), postStore(), getShow(), getEdit(), putUpdate(), getDestroy(), getLogin(), getDashboard(), and getLogout().
I have included the following codes into the routes.php
Route::get('/', function()
{
return View::make('hello');
});
Route::get('users/all/', [ 'as' => 'users.index', 'uses' => 'UserController#getAll']);
Route::get('users/create/', [ 'as' => 'users.getCreate', 'uses' => 'UserController#getCreate']);
Route::get('users/{all}/edit', 'UserController#getEdit');
Route::put('users/update/{id}', [ 'as' => 'users.putUpdate', 'uses' => 'UserController#putUpdate']);
Route::controller('users', 'UserController');
I can access the pages like
http://localhost/testlaravell/users/
or
http://localhost/testlaravell/users/add
etc.
Now, I want that only logged in users can access the pages, other wise s/he will be redirect to the login page http://localhost/testlaravell/login
The methods for login under UserController.php as follows:
public function postSignin() {
$rules = array(
'username' => 'required', // make sure the username is an actual username
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('users/login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
return Redirect::to('users/dashboard')->with('message', 'Welcome User');
} else {
// validation not successful, send back to form
return Redirect::to('users/login')->with('message', 'Sorry!! Username/ Password seems wrong.');
}
}
}
public function getLogin() {
return View::make('users.login');
}
You'll want to make use of the Auth Filter in Laravel 4
You can wrap all your routes in a group and specify that filter, in your case the code would be something like this.
Route::group(array('before' => 'auth'), function()
{
Route::get('users/all/', [ 'as' => 'users.index', 'uses' => 'UserController#getAll']);
Route::get('users/create/', [ 'as' => 'users.getCreate', 'uses' => 'UserController#getCreate']);
Route::get('users/{all}/edit', 'UserController#getEdit');
Route::put('users/update/{id}', [ 'as' => 'users.putUpdate', 'uses' => 'UserController#putUpdate']);
Route::controller('users', 'UserController');
});
You can checkout the documentation on Route Groups here

Resources