How do I get a variable from a table related to the auth user in laravel? - 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'],
]);
}

Related

laravel 8 Sorry! You have entered invalid credentials

I am using a custom Authentication in Laravel 8 and whenever I try to Enter a valid email/password am getting this error: Sorry! You have entered invalid credentials.
here is my code:
1#Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use Hash;
use Validator;
class AuthController extends Controller
{
/**
* Write code on Method
*
* #return response()
*/
public function index()
{
return view('auth.login');
}
/**
* Write code on Method
*
* #return response()
*/
public function registration()
{
return view('auth.register');
}
/**
* Write code on Method
*
* #return response()
*/
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('You have Successfully logged in');
}
return redirect("login")->withSuccess('Sorry! You have entered invalid credentials');
}
/**
* Write code on Method
*
* #return response()
*/
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'username' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("login")->withSuccess('Great! please login.');
}
/**
* Write code on Method
*
* #return response()
*/
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('Opps! You do not have access');
}
/**
* Write code on Method
*
* #return response()
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Write code on Method
*
* #return response()
*/
public function logout() {
Session::flush();
Auth::logout();
return Redirect('login');
}
}
2#Login.blade.php:
#extends('layouts.layout')
#section('content')
<div class="login-form">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">
#if (Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
<form action="{{ route('login.post') }}" method="POST">
#csrf
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required />
#if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</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 type="password" id="password" class="form-control" name="password" required />
#if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
For registration it's working fine, the only problem is in Login form. Hope you can help.
First step: check your user model extends from Authenticable that main user model uses,
Second step:use bcrypt instead of Hash::make,
If solutions doesnt work send your model and config/auth.php for better answer

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 deal with controller resource in laravel

I am using the resource tool for my controller and my route but the store method appears not to work. Could you highlight what I did wrong. Is the controller name needs to be the same as the model one? I am confuse
FarmController
<?php
namespace App\Http\Controllers;
use App\Animal;
use Auth;
use Illuminate\Http\Request;
class FarmController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$animal = Animal::all();
return view('farms.index', compact('animal'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$user = Auth::user();
$animal = new Animal();
return view('farms.create', compact('user', 'animal'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
Animal::create($this->validateRequest());
return redirect('farms.show');
}
private function validateRequest()
{
return request()->validate([
'dateOfBirth' => 'required|date',
'placeOfBirth' => 'required',
'gender' => 'required',
'user_id' => 'required',
]);
}
Animal.php (controller)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Animal extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}}
animals (table)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAnimalsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('animals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->index();
$table->date('dateOfBirth');
$table->string('gender');
$table->string('placeOfBirth');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('animals');
}
}
create.blade.php
#extends('layouts.app')
#section('title', 'Add Animal')
#section('content')
<div class="row">
<div class="col-12">
<h1>Farm</h1>
</div>
</div>
<h3>Welcome {{ $user->name }} Please Add an animal</h3>
<div class="row">
<div class="col-12">
<form action="{{ url('farms') }}" method="POST">
<div class="form-group">
<label for="dateOfBirth">Date Of Birth: </label>
<input type="date" name="dateOfBirth" class="form-control" placeholder="dd/mm/yyyy">
</div>
<div class="pb-5">
{{ $errors->first('dateOfBirth') }}
</div>
<div class="form-group">
<label for="placeOfBirth">Place Of Birth</label>
<input type="text" name="placeOfBirth" class="form-control">
</div>
<div class="pb-5">
{{ $errors->first('placeOfBirth') }}
</div>
<div class="form-group">
<label for="gender">Gender: </label>
<select name="gender" class="form-control">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group">
<label for="user">User</label>
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Add Farm</button>
#csrf
</form>
</div>
</div>
#endsection
web.php (routes)
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::middleware('admin')->group(function () {
// All your admin routes go here.
Route::resource('/admin', 'AdminController');
});
Route::middleware('farms')->group(function () {
// All your admin routes go here.
Route::resource('/farms', 'FarmController');
});
When I am submitting the form, it seems like it just refreshes the page and do not add anything in my table. I have been stuck on this in two entire days. any help is welcome
In the validateRequest function you have
'user_id' => 'required',
But your form in the view has no field named user_id
The select element is named user
<select class="form-control" name="user">
<option value="{{ $user->id }}" name="user">{{ $user->name }}</option>
</select>
Change one of them so they can match, I guess that the page refresh is just failed validation
You may want to check for any validation error in your view to find out what's wrong as per the docs
For example
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Hope this helps
Just change your form action then it hit in correct mehtod. Here is the action for your form
{{route('farms.store')}}

How to store data in foreign key of a user table

The question is pretty simple. I am storing user's form data into table. I am using Auth login system of laravel, when user fill the input fields and register all values received in array called $data in create function (as you know code written in laravel as default) but when I save it in table, all values save expect department_id that is a foreign key. There is also a candidate_id and it is also a foreign key of candidate_table and it also save, but department_id have some issue.
Blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('register') }}">
{{ csrf_field() }}
{{--<input style="text-transform: capitalize;" id="test" type="number" class="form-control" name="id" required autofocus>--}}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input style="text-transform: capitalize;" id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<input style="text-transform: capitalize;" id="department" type="number" class="form-control" name="department" required autofocus>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function candidate()
{
return $this->belongsTo(Candidate::class,'candidate_id');
}
public function department()
{
return $this->belongsTo(Department::class,'department_id');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','email','password','image','candidate_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Department;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
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:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
// 'candidate_id' => $data['id'],
'password' => bcrypt($data['password']),
'department_id' => $data['department'],
]);
}
}
As you can see, for department_id input you have commented out form input field.
{{--<input style="text-transform: capitalize;" id="test" type="number" class="form-control" name="id" required autofocus>--}}
Uncomment the code and it will work fine.
And because of it, it will not store department_id
Try changing...
protected $fillable = [
'name','email','password','image','candidate_id'
];
to
protected $fillable = [
'name','email','password','image','candidate_id','department_id'
];

Resources