laravel select box value not adding to database - laravel

so am trying to send the value of a select box to database to calculate admin roles but it doesn't receive the value here is my view
<div class="form-group row">
<label for="exampleFormControlSelect1" class="col-md-4 col-form-label text-md-right">Role</label>
<div class="col-md-6">
<select class="form-control" id="exampleFormControlSelect1" name="role">
<option value="1">Super Admin</option>
<option value="2">Admin</option>
<option value="3">Doctor</option>
<option value="4">Sales</option>
</select>
</div>
</div>
and this is my controller its for adding new admins to the database (not users with admin roles)
public function showRegistrationForm()
{
return view('auth.admin-register');
}
public function register(Request $request)
{
// Validate form data
$this->validate($request,
[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'password' => ['required', 'string', 'min:8'],
'role' => ['required']
]
);
dd($request->role);
// Create admin user
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);
return redirect()->route('admin.dashboard');
} catch (\Exception $e) {
return redirect()->back()->withInput($request->only('name', 'email'));
}
}
the dd($request->role) works and return the nvalue of the but the problem is with the
try {
$admin = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => $request->role
]);

In model you can define protected columns then all the other column will be auto fillable
or you can define fillable columns in model

The problem was that I didn't set the role in fillable in admin model

Related

laravel link a registration form to database field

I am using teams in laravel and want to add a company name field to my registration form instead of it running the standard:
'name' => explode(' ', $user->name, 2)[0]."'s Team",
I am still wanting to keep the field called name but use the input fields data, I have tried changing the method to:
protected function createTeam(User $user)
{
$user->ownedTeams()->save(Team::forceCreate([
'user_id' => $user->id,
'name' => $user['company_name'],
'personal_team' => true,
]));
}
but it doesn't work as intended. My register.blade.php is:
<div>
<x-jet-label value="{{ __('Company Name') }}" />
<x-jet-input class="block mt-1 w-full" type="text" name="company_name" :value="old('company_name')" autofocus autocomplete="company_name" />
</div>
my migration is unchanged as I am wanting to force the name through my form instead of it generating it based on the user input of name.
The complete CreateNewUser method is:
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
])->validate();
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$this->createTeam($user);
});
});
}
/**
* Create a personal team for the user.
*
* #param \App\Models\User $user
* #return void
*/
protected function createTeam(User $user)
{
$user->ownedTeams()->save(Team::forceCreate([
'user_id' => $user->id,
'name' => $user['company_name'],
'personal_team' => true,
]));
}
}

How to send a query in a variable using laravel?

I have this function to register my users
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'apellido' => ['required', 'string', 'max:255'],
'idop' => ['required', 'string', 'max:6', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'cedula' => ['required', 'int'],
'fecha_nacimiento' => ['required', 'date'],
'fecha_ingreso' => ['required', 'date'],
'extension' => ['required', 'int'],
'movil' => ['required', 'int'],
'tel_hab' => ['required', 'int']
]);
}
I would like to send this query in a variable ($generos) to make a select
$generos = DB::table('tbl_lista_generos')
->select('id','genero')
->get();
How could I do that?
You can pass the variable from controller to view using below ways:
Way1
$generos = DB::table('tbl_lista_generos')
->select('id','genero')
->get();
return view("index", compact("generos "));
Way2
$generos = DB::table('tbl_lista_generos')
->select('id','genero')
->get();
return view("index", ["generos" => $generos]);
Way3
$generos = DB::table('tbl_lista_generos')
->select('id','genero')
->get();
return view("index")->with(["generos" => $generos]);
On your view file::
<select name="genero">
<option value=''>select</option>
#foreach ($generos as $genero)
<option value="{{ $genero->id }}">{{ $genero->name}}</option>
#enforeach
</select>
by the comments, you want to send the result of the query to the view. So,
In your controller function do:
return view('generos.index', [
'generos' => DB::table('tbl_lista_generos')->select('id','genero')->get()
]);
In the view:
<select class='' name='select_form_generos'>
<option value=''>select genero</option>
#foreach ($generos as $genero)
<option value='{{ $genero->id }}'>{{ $genero->genero}}</option>
#enforeach
</select>
Hope it helped!

Store image path in a DB

I’m working on a CRUD system for inventory management, in which images for each product should be included. Every time that I try to save the path of the image in the DB this error appears:
Undefined variable: image
My controller looks like this:
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required',
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
}
$product['Product_Image'] = $image;
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}
and my input looks like this:
<form method="post" action="{{url('loginv')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="row">
<div class="col-md-12"></div>
<div class="form-group col-md-12">
<label for="Product_Image">Product Image:</label>
<input type="file" class="form-control" name="Product_Image">
</div>
</div>
and dd($request->all()); delivers this
array:8 [▼ "_token" => "P7m8GP4A35G1ETUosduBSWtMpJuPaNILn2WI6Al3"
"Product_Image" => "6.jpg" "Product_Name" => "asd" "Amount" =>
"123" "MinAmount" => "1" "Status" => "Ok" "Supplier" => "asd"
"WebLink" => "asd" ]
Change your code to
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required'
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
$product['Product_Image'] = $image;
}
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}

Solving Method Not Allowed Http Exception in Laravel 5.2

I want some values in my table editable, so I created this simple custom form. But this will throw error of method not allowed http exception.Any help?
<form action="{{ url('/idx-test/update-this-student/'. $student->id)}}" class="" method="POST">//changing this to put, patch does not solve the error
Route
Route::post('/idx-test/update-this-student/{id}', 'StudentController#updateThisStudent'); //again changing this to patch,or put does not help
Controller
public function updateThisStudent(StudentRequest $request, $id)
{
$student = Student::findOrFail($id);
$student->update($request->all());
// return redirect('city');
echo "updated";
}
StudentRequest
public function rules()
{
return [
'firstname' => 'required|alpha|min:2|max:10',
'lastname' => 'required|alpha|min:2|max:10',
'bday' => 'required|date',
'address' => 'required|min:10',
'zip' => 'required|min:4|max:10',
'phone' => 'required|digits:7',
'mobile' => 'required|digits:11',
'email' => 'required|email',
'city_id' => 'required',
'yearlevel_id' => 'required',
'section_id' => 'required',
];
}
By adding this small piece of code
<input type="hidden" name="_method" value="PATCH">
My problem solve

Laravel Spark - Adding additional fields to registration form, but when empty no errors are returned

I'm building my first app with Laravel 5.2 & Laravel Spark. The front end is built using Vue.js I believe and despite adding the following to register-common-form.blade.php:
<!-- Username -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('username')}">
<label class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input type="name" class="form-control" name="username" v-model="registerForm.username" autofocus>
<span class="help-block" v-show="registerForm.errors.has('username')">
#{{ registerForm.errors.get('username') }}
</span>
</div>
</div>
I can't actually see a way to fully register that extra field so that it is picked up for error handling. I've got it so that the UserRepository handles the field and inserts it, but just can't get the front end errors to show properly.
Is anyone able to help with this at all?
Okay I finally stumbled across it :D
In Laravel\Spark\Interactions\Auth\CreateUser.php there is a $rules method like so:
public function rules($request)
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
All I have done is add my username field, and it works brilliantly!
public function rules($request)
{
return [
'name' => 'required|max:255',
'username' => 'required|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
Above answer is just for validation rules you also need to navigate to spark\src\Repositories\UserRepository.php and add 'username' => $data['username'], to the create() method like this:
public function create(array $data)
{
$user = Spark::user();
$user->forceFill([
'name' => $data['name'],
'username' => $data['username'], // ADDED THIS
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => str_random(30),
'last_read_announcements_at' => Carbon::now(),
'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
])->save();
return $user;
}

Resources