Failed to save information to database - laravel

I'm quite new to laravel, created all that is needed but i can't edit or add new entries into the database. However i can successfully delete. what could be the problem not making the application write to the database?
This is my store function
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
// redirect
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
return Redirect::to('user');
}
Route
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('auth.login');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::resource('user', 'UserController');
Route::resource('role', 'RoleController');

User Controller
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
// redirect
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
return Redirect::to('user');
}
Your routes
<?php
Route::get('/', function () {
return view('auth.login');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::post('/user/store', 'UserController#store');
Your form
<form id="form-add-user" role="form" method="POST" action="{{ url('/user/store') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
...
</form>

Change your store method with below given and let me know which message will print?
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
//Success redirect
if($user){
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
}
//Failed redirect
else {
Session::flash('message', 'Something went wrong!');
Session::flash('alert-type', 'success');
}
return Redirect::to('user');
}
For get the ride of basic CRUD with laravel example.

Related

Laravel 9: Auth::user() / auth()->user() null after successfull login

I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.

How to login right after registration in Laravel?

I am trying to register a new user into my system, and right after make the login automatically. How can I call another function in the same Controller and pass $request variables to it?
I did the var_dump, login function is getting data, the login is being made, but it's not redirecting to index (line 28)
public function login(Request $request)
{
//var_dump($request->only('email', 'password'));
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if(Auth::attempt($credentials)) {
return redirect()->route('movie.index');
}
return redirect()->route('login')->with([
'error' => 'danger',
'msg' => 'Error message',
]);
}
public function register(Request $request)
{
$newUser = new User;
$newUser->name = $request->name;
$newUser->email = $request->email;
$newUser->password = Hash::make($request->password);
$newUser->save();
$this->login($request);
}
Right way is
Auth::login($newUser);
Then redirect to your page after login.

laravel 8 form validation stop working and throw an error

here is my code for validate request
public function signup(Request $request) {
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
]);
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
when I try this validation not working how can I fix this?
for example
when this data for validation
'name' = "",(empty)
'email' = "test2#mail.com"
'password'= "test2#mail.com"
and I expect my validation should work but its throw BadMethodCallException error
here is my route (via API)
<?php
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', [App\Http\Controllers\AuthController::class, 'login']);
Route::post('logout', [App\Http\Controllers\AuthController::class, 'logout']);
Route::post('refresh', [App\Http\Controllers\AuthController::class, 'refresh']);
Route::post('me', [App\Http\Controllers\AuthController::class, 'me']);
//custom
Route::post('signup', [App\Http\Controllers\AuthController::class, 'signup']);
});
NOTE: am check this VIA postman
You can do it another way with the laravel Validator class. Please add use Validator class before your class declaration.
Then create your function like this:
public function signup(Request $request) {
$validate = array(
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
);
$validatedData = Validator::make($request->all(),$validate);
if(!validatedData->fails()) {
return $validatedData->errors();
}else{
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
}

Laravel user update problems

Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone

Laravel 5 Multiple form validation rules

So i have three forms on one page. One is to change user's picture, another one is to update personal informations, and the last form is to set a new password.
My issue here is that i'm getting validation errors on the password and password confirmation fields even though i'm trying to update some information (second form).
I have created two requests:
UserEditRequest:
class UserEditRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required'
];
}
}
UserUpdatePasswordRequest:
class UserUpdatePasswordRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'password' => 'required|confirmed|min:6',
'password_confirmation' => 'required|min:6',
];
}
}
within UserController updatePassword:
public function updatePassword(UserUpdatePasswordRequest $request, $id)
{
$user = User::findOrFail($id);
$user->password = bcrypt($request->get('password'));
$user->save();
return redirect()->route('user.edit',$id)->with('success','Password changed.');
}
postEdit where I handle the personal details and avatar changes:
public function postEdit(UserEditRequest $request, $id)
{
dd($request->all());
$user = User::findOrFail($id);
if($request->get('avatar'))
{
$destinationPath = public_path() . '/avatars/' . $user->id . '/';
$fileName = $user->id . '.' . $request->file('avatar')->getClientOriginalExtension();
$request->file('avatar')->move($destinationPath, $fileName);
$user->avatar = 'avatars/' . $user->id . '/' . $fileName;
$user->save();
return redirect()->route('user.edit',$id)->with('success','User avatar modified.');
}
$user->fill($request->input())->save();
return redirect()->route('user.edit',$id)->with('success','User details modified.');
}
quicky my routes:
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#getEdit']);
Route::post('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#postEdit']);
Route::post('profile/{userid}', ['as' => 'updatepassword', 'uses' => 'UserController#updatePassword']);
});
});
Try to differentiate your routes for the postEdit and the updatePassword controller actions
Route::post('profile/{userid}', ['as'=>'edit', 'uses'=>'UserController#postEdit']);
Route::post('profile/password/{userid}', ['as'=>updatepassword', 'uses'=>'UserController#updatePassword']);
Using the same route for two different controller actions won't work. What I mean is how do you expect the router to determine which controller action to invoke when the form action='/profile/id' method='post' ? Hence you need to differentiate the routes.
Hope you got it.

Resources