public function register(Request $request){
$this->validate($request, [
'username' => 'required|string|unique:users',
'password' => 'required|string|min:8',
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users',
]);
try {
$user = new User;
$user->username= $request->input('username');
$user->password =Hash::make($request->input('password'));
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->save();
} catch (Exception $e) {
return response()->json(['error' => 'Registration Failed'], 403);
}
}
This is the typical response get:
"message": "The given data was invalid.",
"status_code": 500
This doesn’t tell anything about the exact validation rule that failed.
How can I solve this?
public function SaveContext(Request $request): JsonResponse
{
try{
$rule = array(
'userName' => 'required|string|max:4',
'password' => 'required |string|max:4'
);
$messages = array(
'userName.required' => 'User name is required.',
'userName.max' => 'User name must not be less than 4 characters.',
'password.required' => 'password is required.',
'password.max' => 'password must not be less than 4 characters.',
);
$this->validate($request, $rule, $messages );
return response()->json(
AppResponse::Success($this->context->SaveContext((object)$request->all()))
);
}catch(\Illuminate\Validation\ValidationException $ex){
return response()->json(
AppResponse::Error($ex->errors())
);
}
}
You can do something like this:
try {
$this->validate($request, [
'username' => 'required|string|unique:users',
'password' => 'required|string|min:8',
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users',
]);
}
catch (\Illuminate\Validation\ValidationException $ex ) {
$errors = $ex->errors();
return response()->json($errors, 422);
}
Related
I would like to update a form, I mentioned that the form is already saved in the database(function store). I want to edit the form and update it in the database(function update).
I only want to UPDATE the "tags", this is giving me an error because it is in another table.
I would need your help because I can't do it, I tried different methods but didn't succeed.
public function store(Request $request)
{
// process the listing creation form
$validationArray = [
'title' => 'required',
'company' => 'required',
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:9048',
'location' => 'required',
'service' => 'required',
'apply_link' => 'required|url',
'content' => 'required',
'payment_method_id' => 'required'
];
if (!Auth::check()) {
$validationArray = array_merge($validationArray, [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:5',
'name' => 'required',
'phone' => 'required|numeric|min:10|starts_with:0'
]);
}
$request->validate($validationArray);
// is a user signed in ? if not, create one and authenticate
$user = Auth::user();
if (!$user) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
]);
$user->createAsStripeCustomer();
Auth::login($user);
}
// process the payment and create the listing
try {
$amount = 9900; // $99.00 USD in cents
if ($request->filled('is_highlighted')) {
$amount += 1000;
}
$user->charge($amount, $request->payment_method_id);
$md = new \ParsedownExtra();
$listing = $user->listings()
->create([
'title' => $request->title,
'slug' => Str::slug($request->title) . '-' . rand(1111, 9999),
'company' => $request->company,
'logo' => basename($request->file('logo')->store('public')),
'location' => $request->location,
'apply_link' => $request->apply_link,
'content' => $md->text($request->input('content')),
'is_highlighted' => $request->filled('is_highlighted'),
'is_active' => true
]);
**foreach (explode(',', $request->tags) as $requestTag) {
$tag = Tag::firstOrCreate([
'slug' => Str::slug(trim($requestTag))
], [
'name' => ucwords(trim($requestTag))
]);
$tag->listings()->attach($listing->id);
}**
foreach (explode(',', $request->service) as $requestService) {
$service = Service::firstOrCreate([
'service_name' => ucwords(trim($requestService))
]);
$service->listings()->attach($listing->id);
}
return redirect()->route('user.dashboard')->with('success', 'Anuntul tau a fost publicat!');
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['error' => $e->getMessage()]);
}
} $tag->listings()->attach($listing->id);
}
public function edit($id)
{
$listing = Listing::findOrFail($id);
if (Auth::check() && Auth::user()->id == $listing->user_id) {
$listing = DB::table('listings')
->where('id', $id)
->first();
return view('listings.edit', compact('listing'));
} else {
return (redirect('/dashboard'));
}
}
public function update(Request $request, $id)
{
//working in progress...
$this->validate($request,[
'title' => 'required',
'company' => 'required',
'logo' => 'file|max:2048|required|mimes:jpeg,jpg,png',
'location' => 'required',
'apply_link' => 'required|url',
'content' => 'required'
// 'payment_method_id' => 'required'
]);
$data = Listing::find($id);
$data->title = $request->title;
$data->company = $request->company;
$data->logo = basename($request->file('logo')->store('public'));
$data->location = $request->location;
$data->apply_link = $request->apply_link;
$data['tags'] = explode(',', $request->tags); // <-this one
$data->content= $request->content;
// $data['is_highlighted'] = $request->is_highlighted;
$data['user_id'] = Auth::user()->id;
$data->save();
// DB::table('listings')->where('id', $id)->update($data);
return redirect()->back()->with('success', 'success');
}
I do not know how i can generate custom secret key for each user when they register. I do not want to use passport, i just want to generate custom .
Here is my code
public function register(Request $request)
{
// $validated = $request->validate([
// 'username' => 'required',
// 'phonenumber' => 'required|digits:10|unique:users',
// 'password' => 'required|string',
// 'device_serial_number' => 'required'
// ]);
$user = User::create([
'username' => $request->username,
'phonenumber' => $request->phonenumber,
'device_serial_number' => $request->device_serial_number,
'password' => bcrypt($request->password)
]);
if($user)
{
// $token = $user->createToken('Laravel Password Grant Client')->accessToken;
$user_secret_key = Str::random(60);
$user->user_secret_key = hash('sha256', $user_secret_key);
return response()->json(['token' => $token], 200);
} else{
return response('error');
}
$user = User::create([
'username' => $request->username,
'phonenumber' => $request->phonenumber,
'device_serial_number' => $request->device_serial_number,
'password' => bcrypt($request->password),
'user_secret_key' => Str::random(60);
]);
if($user){
$token = $user->user_secret_key;
return response()->json(['token' => $token], 200);
} else{
return response('error');
}
Here is my code but its send me error. Its said Wrong parameters for Exception handler.
try {
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email_address' => 'required|unique:users|email',
'username' => 'required|unique:users|max:20',
'phone_number' => 'alpha_num|max:13',
'password' => 'required|min:6|max:18',
]);
if ($validator->fails()) {
throw new Exception('Please checkout your fields again!', $validator->errors() );
}
}catch( Exception $e){
return ['success'=>false, 'message'=>$e->getMessage()];
}
You can use implode function which will join the array as a string
something like this:
try {
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email_address' => 'required|unique:users|email',
'username' => 'required|unique:users|max:20',
'phone_number' => 'alpha_num|max:13',
'password' => 'required|min:6|max:18',
]);
if ($validator->fails()) {
throw new Exception('Please checkout your fields again!', implode(',',$validator->errors()) );
}
}catch( Exception $e){
return ['success'=>false, 'message'=>$e->getMessage()];
}
You should try this may be more help for you:
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email_address' => 'required|unique:users|email',
'username' => 'required|unique:users|max:20',
'phone_number' => 'alpha_num|max:13',
'password' => 'required|min:6|max:18',
]);
if ($validator->fails()) {
return redirect('yourRoute')
->withErrors($validator)
->withInput();
}
For more details, you can follow this link.
I'm trying to make email optional when user signs up. Here is package. So I removed email' => 'required|email|unique:users', in this function:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
then in config-boilerplate.php I also removed email:
'signup_fields_rules' => [
'name' => 'required',
'email' => 'required|email|unique:users',///// this
'password' => 'required|min:6'
],
But when I sign up I get this error :
"message": "Undefined index: email",
"status_code": 500,
"debug": {
"line": 173,
"file": "/Users/MyMac/Desktop/Project/laravel-5.3-boilerplate-api-jwt-vue2/vendor/dingo/api/src/Http/Response/Factory.php",
"class": "Symfony\Component\HttpKernel\Exception\HttpException",
the route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController#signup');
Is there anything I need to disable to allow users sign-up with or without email ?
If you want to make email as optional field, just use sometimes|email See Docs. Try below code:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
config-boilerplate.php
'signup_fields_rules' => [
'name' => 'required',
'email' => 'sometimes|email',///// this
'password' => 'required|min:6'
],
I'm trying to get my registration page to show, the controller logic seems ok but I keep getting this:
BadMethodCallException
Method [ register] does not exist.
here is my controller logic:
<?php
class UserController extends BaseController {
public function register()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.register")->with("title", "Avenue - Register")->with("page_title", "Register");
}
public function postRegister()
{
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('register')->with_input()->with_errors($validation);
}
$user = Sentry::createUser(array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'metadata' => array(
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
'nationality' => Input::get('nationality'),
'gender' => Input::get('gender'),
'category' => Input::get('category'),
),
));
Mail::send('emails.welcome', $data, function($message)
{
$message->to(Input::get('email'))->subject('Welcome to Avenue254!');
});
}
public function getLogin()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.login")->with("title","Avenue254 - Login")->with("page_title","Login");
}
public function postLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Redirect::to_route('login')->with_errors($validation->errors)->with_input();
}
$credentials = array( 'email'=> Input::get('email'), 'password'=>Input::get('password') );
if (Sentry::authenticate($credentials, false))
{
return Redirect::to('myaccount');
}
else
{
return Redirect::to('login')->with("error", "There is problem with login please try again");
}
}
public function getMyaccount()
{
if(!Sentry::check()){
return Redirect::to('login')->with("error", "Please login to access your account");
}
$user = Sentry::getUser();
return View::make("users.myaccount")->with("title","Avenue254" - "My Account")->with("page_title","My Account")->with('user',$user);
}
public function postProfile()
{
$user = Sentry::getUser();
$rules = array(
'email' => 'required|email|unique:users,email,'.$user['id'],
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('myaccount')->with_input()->with_errors($validation);
}
$user_data = array(
'email' => Input::get('email'),
'metadata' => array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
),
);
if ($user->update($user_data))
{
return Redirect::to('myaccount')->with('success', 'Your information has been updated successfully.');
}
else
{
return Redirect::to('myaccount')->with('error', 'Something went wrong!.');
}
}
}
and my routes:
Route::get('register', array('as' => 'getregister', 'uses' => 'UserController#
register'));
Route::get('myaccount', array('as' => 'myaccount', 'uses' => 'UserController#
myaccount'));
Route::post('register', array('as' => 'postregister', 'uses' =>
'UserController#postRegister'));
Whenever I try to route to register I get this error, I have tried everything unsuccessfully. What could I be doing wrong?