Store image path in a DB - laravel

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');
}
}

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,
]));
}
}

laravel select box value not adding to database

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

How to upload multiple images into a database using laravel?

I am trying to Upload multiple images into a database but only one is uploading instead of multiple.
How to upload multiple images into a database?
Could anyone tell me what is wrong with my code?
[database table ][1]
[1]: https://i.stack.imgur.com/kgv4r.png
controller
public function singalprojectaction(Request $request)
{
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$images[]=$name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$images),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query)
{
return response()->json([
'message' => 'Image is Successfully Inserted',
'class_name' => 'alert-success'
]);
}
else{
return response()->json([
'message' => 'Data is not inserted Inserted',
'class_name' => 'alert-warning'
]);
}
}
html view
<form action="Route('singal.action') }}" id="singal_project"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="alert" id="message" style="display:block;"></div>
<div class="group-form">
<label>Drop Multple Imges</label>
<input required type="file" class="form-control" name="images[]"
multiple>
</div>
</form>
Try This To insert multiple images
public function singalprojectaction(Request $request)
{
$input=$request->all();
$datas = [];
$result = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/projects/', $name);
$datas[$key] = $name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$datas);
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query){
return response()->json(['message' => 'Image is Successfully Inserted','class_name' => 'alert-success']);
}
else{
return response()->json(['message' => 'Data is not inserted Inserted','class_name' => 'alert-warning'
]);
}
}
You will have to wrapped the insert code in the foreach statement: see below
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> $name),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
}

CakePHP 3 : default validation not working

I am working in CakePHP 3.2. I have users table and register action in UsersController.
I'm trying to add a new record but default validation is not working.
This is my 'UsersTable.php`
<?php
namespace App\Model\Table;
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
class UsersTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('UserAddresses', [
'foreignKey' => 'user_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->uuid('id')
->allowEmpty('id', 'create');
$validator
->notEmpty('name');
$validator
->email('email')
->notEmpty('email');
$validator
->add('mobile', [
'minLength' => [
'rule' => ['minLength', 10],
'message' => 'Mobile number must be of 10 characters long',
],
'maxLength' => [
'rule' => ['maxLength', 10],
'message' => 'Mobile number must be of 10 characters long',
]
])
->numeric('mobile')
->notEmpty('mobile');
$validator
->notEmpty('password');
$validator
->add('newPassword', [
'compare' => [
'rule' => ['compareWith', 'confirmNewPassword'],
]
])
->notEmpty('newPassword');
$validator
->add('confirmNewPassword', [
'compare' => [
'rule' => ['compareWith', 'newPassword'],
'message' => 'Password does not match'
]
])
->notEmpty('confirmNewPassword');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
public function validationPassword(Validator $validator)
{
$validator
->add('old_password', 'custom', [
'rule' => function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message' => 'The old password does not match the current password!',
])
->notEmpty('old_password');
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password1', [
'match' => [
'rule' => ['compareWith', 'password2'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password2', [
'match' => [
'rule' => ['compareWith', 'password1'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password2');
return $validator;
}
}
register() method
public function register()
{
// if already logged in, redirect to referer action to prevent new registration
if (!empty($this->Auth->user('id'))) {
return $this->redirect($this->referer());
}
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// check user exists or not
$userExists = $this->Users->find('all', [
'conditions' => [
'OR' => [
'email' => $this->request->data['email'],
'mobile' => $this->request->data['mobile'],
]
]
]);
if ($userExists->count() > 0) {
$userExists = $userExists->first();
$this->Flash->success(__('It seems you are already registered. Please login using your email or mobile and passowrd'));
return $this->redirect(['controller' => 'Users', 'action' => 'login']);
}
$hash = hash('sha256',date('YmdHis').time());
$user->tmp_hash = $hash;
$user->verified = 0;
$user = $this->Users->patchEntity($user, $this->request->data);
if ($u = $this->Users->save($user)) {
// send verification email
if ($this->sendEmail($user->id, $user->email, $hash, 'register')) {
$this->Flash->registerSuccess(__('Thank you. You need to verify email. Not received verification email ?'), [
'params' => [
'userId' => $user->id
],
['escape' => false]
]);
return $this->redirect(['action' => 'login']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
return $this->redirect(['action' => 'login']);
}
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
register.ctp view
<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']) ?>
<div class="form-group">
<label>Name <?= $this->Form->error('name') ?></label>
<?= $this->Form->input('name', ['class' => 'form-control', 'label' => false, 'placeholder' => 'Enter Your Name', 'title' => 'Please Enter your full name']) ?>
</div>
<div class="form-group">
<label>Email address</label>
<?= $this->Form->input('email', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Enter Email', 'title' => 'Please enter valid email']) ?>
</div>
<div class="form-group">
<label>Mobile</label>
<?= $this->Form->input('mobile', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Mobile Number', 'title' => 'Please enter valid mobile no to receive notifications']) ?>
</div>
<div class="form-group">
<label>Password</label>
<?= $this->Form->input('password', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Password', 'title' => 'Please enter password']) ?>
</div>
<?= $this->Form->button('<i class="fa fa-user"></i> Create and account', ['type' => 'submit', 'class' => 'btn btn-primary', 'escape' => false]) ?>
<?= $this->Form->end() ?>
</div>
When I try to submit form without filling anything, it simply refreshes the form without showing validation error.
In your register.ctp file
$this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
Replace it with
$this->Form->create($user, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
As per concept of CakePHP v3 you have to pass entity in Form Creation method so it will display form validation error in view.

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

Resources