How to Redirect a new user to the edit profile page - laravel

I am having a problem here. When a new user register I want to redirect him/her to the edit profile page... how do I change the login controller to redirect to that page?
here is my RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/profiles/'.$user->id.'/edit';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'type' => ['required'],
'name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phone' => ['required', 'string', 'max:15', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'type' => $data['type'],
'password' => Hash::make($data['password']),
]);
if($data['type'] == 'Learner'){
$user->attachRole('learner');
return $user;
}
elseif($data['type'] == 'Guardian'){
$user->attachRole('guardian');
return $user;
}
elseif($data['type'] == 'Teacher'){
$user->attachRole('teacher');
return $user;
}
}
}
edit.blade.php
#extends('layouts.admin')
#section('main-content')
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">{{ $user->name }} {{$user->last_name}}</h1>
<hr/>
#if (session('message'))
<div class="alert alert-success border-left-success alert-dismissible fade show" role="alert">
{{ session('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<form method="POST" action="{{ route('profiles.update', $user->id) }}">
#csrf
#method('PATCH')
<div class="row">
<div class="col-md-9">
<div class="card shadow mb-4 px-4 pb-4">
<div class="card-header py-3 px-0">
<h6 class="m-0 font-weight-bold text-primary">User Information</h6>
</div>
#if(Auth::user()->hasRole(['superadministrator', 'administrator']))
<div class="row my-2">
<div class="col-md-2 font-weight-bold pt-2">Role:</div>
<div class="col-md-10">
<div class="form-group">
<select id="role" name="role" class="form-control #error('role') is-invalid #enderror" value="{{ old('role') }}">
<option value="">Choose user role...</option>
#foreach($roles as $role)
<option value="{{ $role->display_name }}" {{ $user->hasRole($role->name) ? 'selected' : '' }}>{{ $role->display_name }}</option>
#endforeach
</select>
#error('role')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
. . . . .
The user must come to this page after registration not to the home directory... please help

In create method change the redirect variable like this:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'type' => $data['type'],
'password' => Hash::make($data['password']),
]);
// change redirect variable
$this->redirectTo = '/profiles/'.$user->id.'/edit';
if($data['type'] == 'Learner'){
$user->attachRole('learner');
return $user;
}
elseif($data['type'] == 'Guardian'){
$user->attachRole('guardian');
return $user;
}
elseif($data['type'] == 'Teacher'){
$user->attachRole('teacher');
return $user;
}
}

A solution :
Create a migration how add $table->boolean('profil_edited')->default(0);
Update your model to add this field on the $fillable array
Check this value :
when users login, and redirect the user to the profile page
or in a middleware

Related

How to use a boolean to pass data to table, using the pre-made laravel register set-up

newbie here. So I have been editing the built in user-table created with vue --auth. So far, I have added my own text columns which was easy enough, but now I am faced with using a boolean. I have looked everywhere and I cannot find a simple way to pass data through a checkbox form to the table.
Here is my migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->mediumText('bio');
//$table->boolean('is_expert')->default(false);
//$table->tinyInteger('is_customer');
//$table->binary('photo')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
The commented out boolean is what I want to use
So I run this code (after removing the //)
Then I need to create a form in my register.blade.php.
here's what it looks like so far:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="first_name" class="col-md-4 col-form-label text-md-right">{{ __('First Name') }}</label>
<div class="col-md-6">
<input id="first-name" type="text" class="form-control #error('first-name') is-invalid #enderror" name="first_name" required>
#error('first-name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="last_name" class="col-md-4 col-form-label text-md-right">{{ __('Last Name') }}</label>
<div class="col-md-6">
<input id="last-name" type="text" class="form-control #error('last-name') is-invalid #enderror" name="last_name" required>
#error('last-name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="bio" class="col-md-4 col-form-label text-md-right">{{ __('Bio') }}</label>
<div class="col-md-6">
<input id="bio" type="text" class="form-control #error('bio') is-invalid #enderror" name="bio" required>
#error('bio')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
more content after here but similar text forms
and here is my controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:30'],
'last_name' => ['required', 'string', 'max:30'],
'bio' => ['required', 'string', 'max:200'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'bio' => $data['bio'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Apologies for the amount of code pasted here! my question is. How would I set out the form in the register.blade file and then, what will I need in the controller? Will I also need to enter anything into the model. Once again apologies for the dumb question and vague details, I couldn't find the answer to this question when looking
Not sure if I understand. If you want to give user a possibility of setting if he is an expert during registration, this is what you need to do:
View:
<input type="checkbox" name="is_expert"></input>
Controller:
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'bio' => $data['bio'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'is_expert' => $data['is_expert']
]);
}
User Model:
If you want to use mass assignment you need to add "is_expert" to "fillable" property in your User model. Probably it will look something like this:
class User extends Model{
protected $fillable = ['first_name', 'last_name', 'bio', 'email', 'password', 'is_expert'];
But note that this is big security gap - password need to be specified by another way e.g. "$user->setPassword();" and then "$user->save();"
Also remember to uncomment "is_expert" in your migration file.

laravel - SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value

*Asking for your help again please. Im getting the above error on registration module. This is working before. I tried to make a my profile edit page and then this happens. Hoping for your help please.. Thank you in advance *
User Controller:
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Model\user\user;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
return view('user.user.show',compact('user'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
auth()->login($user);
return redirect(route('index'));;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = Auth::user();
return view('user.user.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate(request(), [
'email' => ['required','email',Rule::unique('users')->ignore($id)],
'password' => ['required','password',Rule::unique('users')->ignore($id)]
]);
//$user = Auth::user();
$user = Auth::user();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->firstname = $request->firstname;
$user->middlename = $request->middlename;
$user->lastname = $request->lastname;
$user->nationality = $request->nationality;
$user->gender = $request->gender;
$user->civilstatus = $request->name;
$user->mobilenum = $request->mobilenum;
$user->worknum = $request->worknun;
$user->workadd = $request->workadd;
$user->homeadd = $request->homeadd;
$user->email = $request->email;
$user->birthday = $request->birthday;
$user->save();
return redirect(route('user.user.show'))->with('message','Announcement Updated Succesfully');;
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
Blade file:
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="text-center"><button class="btn btn-primary text-left" style="width: 100%;" type="button"><i class="fa fa-facebook"></i> Continue with Facebook</button></div>
<div class="text-center mt-2"><button class="btn btn-light text-left border-dark" style="width: 100%;" type="button"><i class="fa fa-google"></i> Continue with Google</button></div>
<form class="mt-4">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-user-o"></i></span></div><input class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus placeholder="Full Name">
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-envelope-o"></i></span></div><input class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" placeholder="Email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-lock"></i></span></div><input class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password" placeholder="Password" type="password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="input-group-append"></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend"><span class="text-primary input-group-text"><i class="fa fa-lock"></i></span></div><input class="form-control" name="password_confirmation" required autocomplete="new-password" placeholder="Confirm Password" type="password">
<div class="input-group-append"></div>
</div>
</div>
Model/users/user.php
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'firstname', 'middlename', 'lastname', 'birthday', 'nationality',
'gender', 'civilstatus', 'mobilenum', 'worknum', 'workadd',
'homeadd',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Please help me. Thank you in advance
The reason you're getting this issue is because password isn't mass assignable i.e. it isn't in your $fillable array.
Methods like create() or fill() are protected from mass assignment. To get around this you can either add password to your $fillable array or set it explicitly e.g.
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = new User([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
$user->save();
auth()->login($user);
return redirect(route('index'));;
}
You can do two things:
Make your table definition so the password can be nullable
Use the new User([...]) syntax over User::create([...]). The first one does not insert directly, the latter will.
Table definition example:
Schema::create('users', function ($table) {
// other user table fields ...
$table->string('password')->nullable();
});
Example without ::create (as given by #Rwd):
// NOT User::create([...]) but new User([...]);
$user = new User([
'name' => request('name'),
'email' => request('email'),
]);
$user->password = bcrypt(request('password'));
$user->save(); // dont forget to save when not using ::create([...]) syntax

How do I get a variable from a table related to the auth user in laravel?

I am working on a project and here are the fields touched
users table-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->unsignedInteger('role_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
role table-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
user model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
];
public function role(){
return $this->belongsTo(Role::class);
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Role model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $guarded = [];
public function users(){
return $this->hasMany(User::class);
}
}
register controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Role;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'role_id' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
$roles = Role::all();
return compact('user', 'roles');
}
}
and here is my register blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="role" class="col-md-4 col-form-label text-md-right">Role</label>
<select name="role_id" id="role_id" class="form-control">
#foreach($roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
</select>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I am getting this error:
Undefined variable: roles (View: /Users/macair13/MeatracProject/resources/views/auth/register.blade.php)
and I have declared roles in my register controller
Please cloud you help me because personally, I am lost
You haven't passed $roles variable in your blade file,
So, fatal error occurs in foreach loop of your blade file,
so to resolve this you have to pass $roles in your blade ,
There many methods to pass $roles to register.blade file.
by override showRegistrationForm() method from below path in your controller
\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
or pass $roles in method inside above vendor path.
for example:
return view('auth.register')->with($roles,Role::get());//don't forget to use Role model.
Or incase if your $roles is not set use isset() condition before your foreach() in blade file like
#isset($roles)
#foreach($roles as $role)
<option value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
#endisset
You need to pass the roles to the view, but what you did is when the user is being created, you try to return the roles. They are not needed then.
So just override the showRegistrationForm() method within your register controller, and it should work.
Add this in your RegisterController.
public function showRegistrationForm()
{
$roles = Role::all();
return view('auth.register', compact('roles'));
}
and this:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
$roles = Role::all();
return compact('user', 'roles');
}
Should be this:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role_id' => $data['role_id'],
]);
}

How to insert a row in Laravel given that one field does not have a default value?

I try to insert the session user id in form but it was show me error this:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into stocks (product_name, product_code, details, price, cost, quntity, updated_at, created_at) values (basmati Rice, 23432, dskljsdlkks;lk; ;ks;lvk, 40, 75, 100kg, 2019-09-09 08:43:12, 2019-09-09 08:43:12))
I think error on this line of code which I used for store the session id
<input type="hidden" name="user_id"
value="{{ $request->session()->put('user',$request->input('id')) }}"
> class="form-control">
This is my create blade page, which I make a form and try to insert the form fields.
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-12">
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
#if(\Session::has('success'))
<div class="alert alert-success">
<p>{{ \Session::get('success') }}</p>
</div>
#endif
<div class="card">
<div class="card-header">
<h5 class="title">Add New Product on Stock</h5>
</div>
<div class="card-body">
<form method="post" action="{{url('stock')}}">
{{csrf_field()}}
<div class="row">
<div class="col-md-6 pr-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" name="user_id"
value="{{Auth::user()->id }}" class="form-control">
<input type="text" name="product_name" class="form-control" placeholder="Enter Product Name" />
</div>
</div>
<div class="col-md-6 pl-1">
<div class="form-group">
<label>Product Code</label>
<input type="text" name="product_code" class="form-control" placeholder="Enter product_code" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" placeholder="Enter price" />
</div>
</div>
<div class="col-md-4 px-1">
<div class="form-group">
<label>Cost</label>
<input type="text" name="cost" class="form-control" placeholder="Enter cost" />
</div>
</div>
<div class="col-md-4 pl-1">
<div class="form-group">
<label>Quantity</label>
<input type="text" name="quntity" class="form-control" placeholder="Enter quntity" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Details</label>
<input type="text" name="details" class="form-control" placeholder="Enter details" />
</div>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#endsection
this is my controller file of stock
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use Auth;
class StockController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stocks = Stock::all()->toArray();
return view('stock.index', compact('stocks'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('stock.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'user_id' =>'required',
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = new Stock([
'user_id' => Auth::user()->user_id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$stock = Stock::find($id);
return view('stock.edit', compact('stock', 'id'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = Stock::find($id);
$stock->product_name = $request->get('product_name');
$stock->product_code = $request->get('product_code');
$stock->details = $request->get('details');
$stock->price = $request->get('price');
$stock->cost = $request->get('cost');
$stock->quntity = $request->get('quntity');
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$stock = Stock::find($id);
$stock->delete();
return redirect()->route('stock.index')->with('success', 'Data Deleted');
}
}
You don't have to use the $request->input('id') to get the user id .
Simply use
Session::flash(Auth::user()->id);
For your code ,
<input type="hidden" name="user_id"
value="{{Auth::user()->id, Session::flash(auth::user()->id) }}"
> class="form-control">
And in your controller ,
when you are trying to save the user_id variable ,
EDIT ::::
$stock = new Stock([
'user_id' => Auth::user()->id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
Use the session variable to store ,.
Or you can directly store the user_id using Auth::user()->id in that line ,
'user_id' => Auth::user()->user_id,
change this:
$request->session()->put('user',$request->input('id'))
to like this:
Session::set('user',$request->input('id'));
Make attention, you need pass the $request to your view, so you can use the request data. Otherwise create a variable $user_id and pass it to your view blade. in this case you can do:
Session::set('user',$user_id);

Laravel 5.2 login issue

Strange issue, when I use the default register route, and I create a user, I can enter inside my app, everything ok. But if I use my CRUD, or the MySQL command for create the user, I can't login.
These credentials do not match our records. (sorry for bad english, I attach the image)
Andrea and Raffaello can login (create with register default route)
Marino can't (generate with my CRUD function) but appear 3 identical records..
routes.php :
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
/* ruote for Admin */
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/', function () {return view('welcome');});
Controller (custom CRUD operation)
<?php
namespace App\Http\Controllers\Dash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Report;
use App\Category;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Session;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UsersController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Display a listing of the resource.
*
* #return void
*/
public function index()
{
$users = User::paginate(15);
return view('dash.users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return void
*/
public function create()
{
return view('dash.users.create');
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
return redirect('dash/users');
}
/**
* Display the specified resource.
*
* #param int $id
*
* #return void
*/
public function show($id)
{
$user = User::findOrFail($id);
return view('dash.users.show', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
*
* #return void
*/
public function edit($id)
{
$user = User::findOrFail($id);
return view('dash.users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
*
* #return void
*/
public function update($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
Session::flash('flash_message', 'User updated!');
return redirect('dash/users');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
*
* #return void
*/
public function destroy($id)
{
User::destroy($id);
Session::flash('flash_message', 'User deleted!');
return redirect('dash/users');
}
}
view:
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Create New User</h1>
<hr/>
{!! Form::open(['url' => '/dash/users', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('email') ? 'has-error' : ''}}">
{!! Form::label('email', trans('users.email'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('email', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('email', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name', trans('users.name'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('name', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('password') ? 'has-error' : ''}}">
{!! Form::label('password', trans('users.password'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('password', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('password', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('surname') ? 'has-error' : ''}}">
{!! Form::label('surname', trans('users.surname'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('surname', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('surname', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#if ($errors->any())
<ul class="alert alert-danger">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
</div>
#endsection
also my custon postLogin() in AuthController for try to overlap default postLogin() - but not working
public function postLogin(LoginRequest $request)
{
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')]))
{
return redirect('/dash-board');
}
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Riprovare?',
]);
}
there is it
you need to specify the data you get from $request
you are storing password not correctly
change this :
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
to this :
$user = new User($request->all());
$user->password = bcrypt($request->pwInputName);
$user->save();
pwInputName : is the password input name in your view
the issue was that you bcrypt all of $request

Resources