data is not submitting into db - laravel

I’m trying to signup user, initially it was working but now its not , when i enter data and click on signup then nothing happens, any solution to resolve this issue?
this is UsersController:
public function register(Request $request){
if($request->isMethod('post')){
$data = $request->all();
/*echo "<pre>"; print_r($data); die;*/
// Check if User already exists
$usersCount = User::where('email',$data['email'])->count();
if($usersCount>0){
return redirect()->back()->with('flash_message_error','Email already exists!');
}else{
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
// Send Confirmation Email
$email = $data['email'];
$messageData = ['email'=>$data['email'],'name'=>$data['name'],'code'=>base64_encode($data['email'])];
Mail::send('emails.confirmation',$messageData,function($message) use($email){
$message->to($email)->subject('Confirm your E-com Account');
});
return redirect()->back()->with('flash_message_success','Please confirm your email to activate your account!');
if(Auth::attempt(['email'=>$data['email'],'password'=>$data['password']])){
Session::put('frontSession',$data['email']);
if(!empty(Session::get('session_id'))){
$session_id = Session::get('session_id');
DB::table('cart')->where('session_id',$session_id)->update(['user_email' => $data['email']]);
}
return redirect('/cart');
}
}
}
}
this is registeration form:
<form id="registerForm" name="registerForm" action="{{ url('/user-register') }}" method="POST">{{ csrf_field() }}
<input id="name" name="name" type="text" placeholder="Name"/>
<input id="email" name="email" type="email" placeholder="Email Address"/>
<input id="myPassword" name="password" type="password" placeholder="Password"/>
<button type="submit" class="btn btn-default">Signup</button>
</form>
and this is route:
Route::post('/user-register','UsersController#register');

The basic registration method in laravel with validation and auto login
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
Auth::login($user);
return redirect()->route('dashboard')
->with('success','Congratulation !!! You are registered successfully. Now you can login');
}
What is the error you will see in the blade template by adding this before form
#if($errors->all())
#foreach ($errors->all() as $error)
<div class="alert alert-danger">{{ $error }}</div>
#endforeach
#endif

Related

Call to a member function getClientOriginalExtension() on null what should do?

public function store(Request $request)
{
$data = new product1();
$file = $request->file;
$filename= time().'.'.$file->getClientOriginalExtension();
$request->file->move('assets', $filename);
$data->file = $filename;
$data->name = $request->name;
$data->description = $request->description;
$data->author = $request->author;
$data->comment = $request->comment;
$data->save();
return redirect()->back();
}
View:
<form action="{{ url('uploadproduct') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input class="form-control" name="comment" placeholder="Write comment" type="text" style=" width: 50%;">
<input class="btn btn-primary" type="submit" value="Done" style=" width: 20%;">
</div>
</form>
$file is null when trying to get its properties.
You can either condition the process to the existence of $file (in case that the 'file' input is not required), or simply check what is happening that input value is null when requesting it.
Maybe there's no <input type="file" name="file"> in your form...
Or maybe your form has no enctype="multipart/form-data" property that allows you to submit files.
I DO also recommend you to validate your request before processing the data: https://laravel.com/docs/8.x/validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'file' => 'required'
]);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator)->withInput();
}
// Here you start processing your inputs
}

After reflecting, I would like to display changes in form page

I would like to make a form.
After submitting the data,Redirect to the same page and reflect a change.
I thought return redirect should be a good way.
but it seems need to fetching the DB.
because 'ErrorException
Trying to get property 'id' of non-object (View:'error happens.
writing $user = \DB::table('users')->where('id', $request->id)... twice
is redundancy and cheesy.
Is there any good way to implement this.
class CertainController extends Controller
{
public function index(Request $request)
{
$user = \DB::table('users')->where('id', $request->id)->first();
$data = ['user' => $user];
return view('user.detail',$data);
}
public function update(Request $request)
{
\DB::table('users')
->where('id', $request->id)
->update([
$request->name => $request->value
]);
return redirect(route('user.detail', [
'user_id' => $request->id,
]));
}
}
web.php
Route::get('/user_detail', 'CertainController#index')->name('user.detail');
Route::get('/user_detail/update', 'CertainController#update')->name('user.detail.update');
blade
<form method ="GET" action={{ route('user.detail.update')}}>
<div class="form-group row">
<label>name</label>
<div class="col-md-6">
<input type = "hidden" name ="id" value="{{ $user->id }}"/>
<input type = "hidden" name = "column" value="name">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ $user->name }}" required autocomplete="name">
#error('')
{{ $message }}
#enderror
<button type = "submit" class ="button">submit</button>
</div>
</div>
</form>
You are looking for id in the index method,
$request->id
^^
But you are sending user_id from update method.
'user_id' => $request->id,
^^^^^
In a simple way, you can just do
return back();
here, back() is a helper function, which redirect back to where it came from.

Got issues with Assigning User to any Shop in Laravel

I have an issue with assign user to any Shop. i created Shop A and Shop B and want to assign user to each shop. Its work fine, when im assign any user to Shop A. however, when i try assign user to Shop B , user alway got in to Shop A not Shop B.
// My User Model
public function shop()
{
return $this->belongsTo(\App\Shop::class, 'user_id');
}
// My Shop Model
public function user()
{
return $this->hasMany(\App\User::class, 'user_id');
}
// My UserController
public function index()
{
$users = User::all();
$shops = Shop::all();
// return view('user', compact('users', 'shops'));
return UserResource::collection($users);
}
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
// My User.blade.php Code
#extends('layouts.app')
#section('content')
<div class="container" style="width: 50%">
<h2>Create User</h2>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="user" method="POST">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<div class="form-group">
<label for="shop">Shop</label>
<select name="shops" class="form-control">
#foreach($shops as $shop)
<option value="{{ $shop->id }}">
{{ $shop->name }}
</option>
#endforeach
</select>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
Am i doing something wrong with Relationship?
You have two distinct relation from the Shop model to the User model.
// Shop Model
public function users()
{
return $this->hasMany(\App\User::class);
}
public function owner()
{
return $this->belongTo(\App\User::class);
}
If in your controller you want to assign the shop to the user created
public function create(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new user();
$user->user_id = auth()->user()->id;
$user->shop_id = $request->shops;
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return new UserResource($user);
}
For the User Model, you need to define the two different relation with Shop Model
public function shop()
{
return $this->belongsTo(\App\Shop::class); //remove the foreign key or change it to 'shop_id'
}
public function ownedShops()
{
return $this->hasMany(\App\Shop::class);
}

Problem with Login after register by Laravel

When I register in laravel ,I can't login by that account.
This is my controller code:
public function register(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'name' => 'required|string|min:3|max:255',
'phone' => 'required|numeric|digits:11|unique:users',
'password' => 'required|string|min:6',
]);
$data = $request->all();
//check unique phone
$usersCount = User::where('phone', $data['phone'])->count();
if ($usersCount > 0) {
return back()->with('flash_message_error', 'این شماره قبلا ثبت شده است');
} else {
$user = new User;
$user->name = $data['name'];
$user->phone = $data['phone'];
$user->password = bcrypt($data['password']);
$user->save();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('profile');
}
}
}
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('/');
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}
And this is blade:
<form action="{{route('userLogin')}}" name="loginForm" method="POST">
#csrf
<input class="form-control" type="number" id="phone" name="phone" placeholder="phone number"/>
<input class="form-control" type="password" id="password" name="password" placeholder="password"/>
<small style="direction: ltr">
<label for="remember" class="form-check-label">remember me</label>
<input id="remember" class="form-check-input" type="checkbox" class="checkbox">
</small>
<button type="submit" class="btn iren-btn btn-block">login</button>
</form>
<form id="registerForm" name="registerForm" action="{{url('user-register')}}" method="post">
#csrf
<input class="form-control" id="name" name="name" type="text" placeholder="name"/>
<input class="form-control" id="phone" name="phone" type="number" placeholder="phone"/>
<input class="form-control mb-2" id="myPassword"
name="password" type="password" placeholder="password" style="direction: ltr"/>
<button type="submit" class="btn iren-btn btn-block">register</button>
</form>
after login it errors 'Not Valid' because of password.When I change password in database by copying from another field that I created by db:seed, it works.
Replace this
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
if (Auth::attempt(['phone' => $data['phone'], 'password' => $data['password']])) {
Session::put('frontSession', $data['phone']);
return redirect('/');
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}
with :
public function login(Request $request)
{
if ($request->isMethod('post')) {
$request->validate([
'phone' => 'required|numeric|digits:11',
'password' => 'required|string',
]);
$data = $request->all();
$user = User::where('phone', $data['phone'])->first();
if ($user) {
if(Hash::check($data['password'], $user->password))
{
Auth::login($user);
Session::put('frontSession', $data['phone']);
return redirect('/');
}
else{
return redirect()->back()->with('flash_message_error', 'password does not match');
}
} else {
return redirect()->back()->with('flash_message_error', 'Not Valid');
}
}
}

"No message" error laravel - trying to update user account information

I'm receiving the error "MethodNotAllowedHttpException
No message" on submit of my user's form, which is meant to update the user's table. I have two post forms on the same page and two post routes, would that have something to do with it?
I will include all the routes and another form that might be conflicting with it.
web.php
Route::get('profile','userController#profile');
Route::post('profile', 'userController#update_avatar');
Route::post('profile-update', 'userController#update_account'); //this ones not working
userController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Image;
class UserController extends Controller
{
//
public function profile()
{
return view('profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request)
{
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('/uploads/avatars/' . $filename) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('profile', array('user' => Auth::user()) );
}
public function update_account(Request $request, $id) //the function with the error
{
User::update([
'id' => Auth::user()->id,
'name' => $request->name,
'email' => $request->email
]);
return redirect('/profile');
}
}
profile.blade.php
<img src="/uploads/avatars/{{ $user->avatar }}" style="width:150px;height:150px;float:left;border-radius:50%;margin-right:25px">
<h2>{{ $user->name }}'s Profile</h2>
<form enctype="multipart/form-data" action="/profile" method="post">
<label>Update Profile Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class=" btn btn-sm btn-light" style="color:#2b2b2b;" value="Update Image">
</form>
<form method="post" action="/profile-update"> <!-- The form with the error -->
{{ method_field('put') }}
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT" />
<label>Username</label>
<input type="text" name="name" class="form-control" value="{{ $user->name }}">
<label>Email</label>
<input type="email" name="email" class="form-control" value="{{ $user->email }}">
<input type="submit" id="update-account" class="btn btn-success" value="Update">
</form>
try this method:
public function update_account(Request $request, $id)
{
$user = User::find($id)
$user->name = $request->name;
$user->email = $request->email;
$user->update();
return redirect('/profile');
}
You don't have any route which can handle the PUT request for "profile-update". In your form you have defined the following function.
{{ method_field('put') }}
This helper function generate an hidden input field which will be used by Laravel to process the current request only as PUT.
To make this work, you either have to make your make your request POST by removing the above helper function or change your route method to PUT.
Route::put('profile-update', 'userController#update_account');
For those that might need the same answer, to fix this I had to play about with it for quite some time and used bits from the suggested answers to solve the issue completely.
I changed the route method to put in web.php.
Replaced my update_account function with #TonzFale answer but replaced $user = User::find($id)with $user = User::find(Auth::user()->id);.

Resources