Reputation: 1993
I am trying to write my own register and login methods in laravel 5, just for learning purposes, and I want to know if I'm on the right track. Specifically with the following:
$this->user->username = $request['username'];
Should I do anything else with this, sanitize, or check if it's a valid username, perhaps?
Secondly, is my public function doRegister
enough like this? Since the validation is done in the RegisterRequest
class?
Routes:
Route::get('register', ['as' => 'register', function() {
return view('register');
}]);
Route::post('register', ['as' => 'register.post', 'uses' => 'AuthController@doRegister']);
AuthController:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Password;
use App\Http\Requests\RegisterRequest;
class AuthController extends Controller
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function doRegister(Password $password, RegisterRequest $request)
{
$this->user->username = $request['username'];
$this->user->password = $password->hash($request['password']);
$this->user->save();
}
}
Password Model:
public function hash($password)
{
$hash = password_hash($password, PASSWORD_BCRYPT);
return $hash;
}
Upvotes: 0
Views: 137
Reputation: 687
The only thing I would add to this code is ensuring that the username isn't taken in the database via the RegisterRequest
class. You can do this by using unique
in your validation rules. Previous versions of Laravel (pre 5.2) have also made use of a service to do the registration, but this appears to have been abandoned for a simpler controller setup in the app's default auth flow.
The reason I say to check in the request is because the controller shouldn't really care about if the data is valid or not. All it cares about is handing the data off to either application code to do work, or to the view to be displayed. The request however does care about the data within it and is the best place to perform this validation. This assumes that you actually want unique usernames, of course.
The only sanitation you should do with a username depends on how you're using it. In regards to the database the model uses the query builder underneath (which uses PDO) so the values should be properly escaped. You could enforce specific characters (or that certain ones aren't used) if you plan on using these as url slugs or parameters. In this case you can validate them in javascript as well as the Request class you've created for this particular request.
Lastly, the controller looks fine if that is what you intend. You might want to redirect them to the login page afterwards or, alternatively, log them in immediately after registering and then redirect them to whatever page they should see. It really all comes down to what process you want the user to go through when creating an account.
Upvotes: 1