Laravel - multiple selection and saving to database - php

I have this small project for car posts. I make my post so everything is working properly, but now i need to have multiple selections. So this is my PostsController:
...
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'brand' => 'required',
'model' => 'required',
'age' => 'required',
'cc' => 'required',
'hp' => 'required',
'body' => 'required',
'fuel' => 'required',
'safety' => 'required'
]);
$post = new Post;
$post->title = $request->input('title');
$post->brand = $request->input('brand');
$post->model = $request->input('model');
$post->age = $request->input('age');
$post->cc = $request->input('cc');
$post->hp = $request->input('hp');
$post->body = $request->input('body');
$post->fuel = $request->input('fuel');
$post->safety = $request->input('safety');
$post->save();
return redirect('/home')->with('success', 'Your post is posted!');
}
...
And now this is my createpost.blade.php :
...
<div class="column">
<label for="safety">Safety:</label></br>
<select class="form-control" name="safety">
<option value="" disabled selected>Select your option</option>
<option value="diesel">ABS</option>
<option value="gasoline">ESP</option>
<option value="electric">CHILD LOCK</option>
<option value="electric">AirBAG</option>
</select>
</div>
...
How can i make this select input for multiple selection and all of the selections need to save into my database? I have my Post.php model:
...
class Post extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
}
Please help if anybody have solutions for this? Or some tutorials or any help similar!

Try some multi select libraries
Select2 is one among them

Use array in your blade.php file and also use multiple
<select class="form-control" name="safety[]" multiple>
In controller
$post->safety = implode(',', $request->input('safety'));

You can use checkbox in blade file
$("input:checkbox").click(function(e){
console.log(e.target.checked ? e.target.value : e.target.value+' is unchecked')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="safety">Safety:</label></br>
<input type="checkbox" value="ABS" name="safety[]" />ABS
<input type="checkbox" value="ESP" name="safety[]" />ESP
<input type="checkbox" value="CHILD LOCK" name="safety[]" />CHILD LOCK
<input type="checkbox" value="AirBAG" name="safety[]" />AirBAG
</div>
And retrieve your data from $request in controller as follows:
$request->input('safety') // return an array with all checked value, e.g: ['ABS','ESP']

add multiple attribute in select tag
change
<select class="form-control" name="safety[]">
to
<select class="form-control" name="safety[]" multiple>
This will let you select multiple options.
User will have to use control/cmd key to select multiple options

Related

How to update only 3 column value in Laravel?

I have a page model. It has following columns in database table:
id
name
email
password
status
privilege
usr_prf_color
usr_prf_nav
usr_prf_scroll
I want to update only 3 column value which are usr_prf_color, usr_prf_nav and usr_prf_scroll.
Here's my controller code:
public function themeUpdate(UpdateThemeRequest $request , User $user)
{
$user->update($request->all());
$request->usr_prf_color;
$request->usr_prf_nav;
$request->usr_prf_scroll;
$this->validate($request, [
'usr_prf_color' =>['required'],
'usr_prf_nav' => ['required'],
'usr_prf_scroll' => ['required'],
]);
$validatedData = $request->validated();
$data = $request-> only(['usr_prf_color','usr_prf_nav','usr_prf_scroll']);
$user->update($data);
$theme = DB::table('users')
->select('usr_prf_color','usr_prf_nav','usr_prf_scroll')
->where('id', $user->id)
->get();
return view('profile.index',compact('theme'));
}
Here's my view code:
<form action="{{ route('profile.themeUpdate', auth()->user()->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Color</label>
<select name="usr_prf_color" class="form-control">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="form-group">
<label>Navigation</label>
<select name="usr_prf_nav" class="form-control">
<option value="horizontal">Horizontal</option>
<option value="vertical">Vertical</option>
<option value="hidden">Hidden</option>
</select>
</div>
<div class="form-group">
<label>Scroll</label>
<select name="usr_prf_scroll" class="form-control">
<option value="scrollable">Scrollable</option>
<option value="non-scrollable">Non-Scrollable</option>
</select>
</div>
</div>
</div>
<button type='submit' class="btn btn-primary">Update</button>
</form>
Here's my route:
Route::put('profile-theme', 'UserProfileController#themeUpdate')->name('profile.themeUpdate');
Here's my model:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'status', 'privilege' ,'password', 'usr_prf_color', 'usr_prf_nav', 'usr_prf_scroll',
];
/**
* 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',
];
}
There's no error when I run this coding, but the data does not stored into database. Can anyone help me to solve this problem. Thank you in advanced.
in your view add id in an input hidden,
in your controller add
User::where('id', $request->input('id'))->update($data);
Try following code:It should work.
$validator = \Validator::make($request->all(),[
'usr_prf_color' =>'required',
'usr_prf_nav' => 'required',
'usr_prf_scroll' => 'required'
]);
if ($validator->fails()) {
return redirect('profile.index')
->withErrors($validator)
->withInput();
}
$user = User::where('id', $request->input('id');
$user->update($request->only(['usr_prf_color','usr_prf_nav','usr_prf_scroll']));
$theme = $user->refresh();
return view('profile.index',compact('theme'));

file input multiple file selection not working

when i die/dump $files i can only see one file in the request when am expecting to see all the files selected. when i die/dump $name in the foreach loop nothing is happening. I need to see all the selected images in the request.
blade create
<form action="/p" enctype="multipart/form-data" method="post" files = "true">
#csrf
<label for="image" class="col-md-4 col-form-label text-md-right">{{ __(' post image') }}</label>
<input type="file", class="form-control-file" id ="image" multiple = "multiple" name="image">
#error('image')
<div class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong> </div>
#enderror
</form>
postcontroller
public function store( Request $request )
{` $request->request->add(['user_id' => $user], ); // Here a request is given a varible either for the admin or user
$data = request()->validate([
'user_id' => 'required',
'about' => 'required',
'category' => '',
'expire_date' => '',
]); `if (Auth::guard('web')->check())
{
$user = Auth::user();
$post = new Post();
/*$post = $user->posts()->create([
'about' => $data['about'],
'category' => $data['category'],
'expire_date' => $data['expire_date'],
]);*/
if($request->hasFile('image'))
{
$files = $request->file('image');
foreach($files as $file)
{
$name = time().'-'.$file->getClientOriginalName();
$name = str_replace('','-',$name);
$file->move('images',$name);
//$post->images->create(['image' => $name ]);
}
} `
$user = Auth::guard('web')->id() ;
// return redirect()->route('home',['user'=>$user]);
}
}
For multiple input, in your html you need to pass it as an array for the name attribute. Change name="image" to name=image[], i.e :
<input type="text" name="image[]" />
This way php will receive an array of image's.
The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'image' => 'array',
];
}

Form validation in select field

Is there a way I can check if a user didn't manipulate the form? In my form, I get all available entries, but if a user changes the value id in the browser, I would just get an error. Any tips:)?
<div class="form-group-row club col-lg-10">
<label>Choose Product</label>
<select name="product_id" class="form-control" required>
#foreach($products as $product)
<option value="{{$product->id}}">{{$product-> product}}</option>
#endforeach
</select>
</div>
You could use a Rule to validate the received data like :
use Illuminate\Validation\Rule;
Validator::make($data, [
'product_id' => [
'required',
Rule::in([/*array of products ids here*/]),
],
]);
Take a look at https://laravel.com/docs/5.8/validation#rule-in
You could use exists like :
Validator::make($data, [
'product_id' => [
'required',
'exists:table_name,column_name'
],
]);
you can do select readonly
<select name="product_id" class="form-control" required readonly>
but user can change html by devtools
also you can check it on backend side like this
if ($products->pluck('id')->diff(request()->input('product_id'))->empty()) {
//not changed
}

problem Integrity constraint violation: 1048 Column

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'patente' cannot be null (SQL: insert into cars (patente, marca, modelo, color, fecha_ingreso, updated_at, created_at) values (?, ?, ?, ?, ?, 2019-06-10 16:27:35, 2019-06-10 16:27:35)
Route::match(['get', 'post'], '/crear',[
'uses'=>'CarController#crear',
'as'=>'cars.crear'
]);
Short code to form
<div class="row">
<div class="col-md-6"></div>
<form action="{{route('cars.crear')}}" method="post">
#csrf
<div class="row form-group">
<div class="col-md-12">
<label for="true">Patente:</label>
<input type="text" name="patente" size="6" maxlength="6" class="form-control" required>
</div>
</div>
code create and show
public function crear(Request $request){
$patente=$request['patente'];
$marca=$request['marca'];
$modelo=$request['modelo'];
$color=$request['color'];
$fecha_ingreso=$request['fecha_ingreso'];
$car=new Car();
$car->patente=$patente;
$car->marca=$marca;
$car->modelo=$modelo;
$car->color=$color;
$car->fecha_ingreso=$fecha_ingreso;
$car->save();
return redirect()->back();
}
public function show(){
$cars=Car::all();
return view ('lista',['cars'=>$cars]);
}
CarController.php
public function crear(Request $request){
request()->validate([
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required',
'patente' => 'required',
'marca' => 'required',
'modelo' => 'required',
'color' => 'required',
'fecha_ingreso' => 'required'
]);
$car = Car::create([
patente => $request->patente,
marca => $request->marca,
modelo => $request->modelo,
color => $request->color,
fecha_ingreso => $request->fecha_ingreso
]);
return redirect()->back();
}
Your code looks fine, a bit verbose, so I cleaned it up a bit and added validation. The only other thing I can think to suggest is ensure your Car model has the fields added to the protected $fillable array.
Just Validate Your data before store it,
php artisan make:request ClearRequest
in App\Requests\ClearRequest,
class ClearRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required',
'patente'=>'required',
'marca'=>'required',
'modelo'=>'required',
'color'=>'required',
'fecha_ingreso'=>'required'
];
}
}
in your controller
use App\Http\Requests\ClearRequest;
in your clear method
public function crear(ClearRequest $request){
...
}
in your view file sth like this,
<form action="/clear" method="POST">
#csrf
patente<br>
<input type="text" name="patente">
<br>
marca<br>
<input type="text" name="marca">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
patente<br>
<input type="text" name="patente">
<br>
modelo<br>
<input type="text" name="modelo">
<br>
color<br>
<input type="text" name="color">
<br>
fecha_ingreso<br>
<input type="text" name="fecha_ingreso">
<br>
<input type="submit" value="Submit">
</form>
if it is helpful yor you upvote me :)
You are trying to store a null value in a NOT NULL column. Make sure you are passing patente correctly in the request.

Column not found: 1054 Unknown column '_token' in 'field list' Laravel

I try to update a record of my table category, but it shows me the error
Column not found: 1054 Unknown column '_token'
Route
Route::post('/categorias/edit/{id}', 'CategoryController#update');
Controller
public function update(Request $request, $id)
{
$data = request()->all();
Categoria::where('id', '=', $id)->update($data);
return redirect()->to('categorias');
}
Model
class Categoria extends Model
{
protected $table = 'categoria';
protected $fillable = ['id','codigo','nombre','descripcion','estado'];
Form
{{ Form::open(array('url' => url('categorias/add') , 'class'=>'form-horizontal' , 'id' => 'formulario' , 'method' => 'POST')) }}
{{ csrf_field() }}
<input id="idcate" name="id" type="hidden" placeholder="" class="form-control input-md" required="">
<input id="txtcodigo" name="codigo" type="text" placeholder="" class="form-control input-md" required="">
<input id="txtnombre" name="nombre" type="text" placeholder="" class="form-control input-md" required="">
<textarea class="form-control" id="txtdescripcion" name="descripcion"></textarea >
<select id="cboestado" name="estado" class="form-control">
<option value="0">NO ACTIVO</option>
<option value="1">ACTIVO</option>
</select>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
{{ Form::close() }}
The records are in a table and I use the same form to edit and to add a new record, only that by clicking the edit button, I change the action
$('#formulario').attr('action', '{{ url("categorias/edit")}}'+ "/"+ $('#idcate').val());
Your error comes from
$data = request()->all();
//which includes '_token'
//coming from csrf_field()
Do instead
$data = request()->except(['_token']);
//same as $request->except('_token');
Just change this at your controller
Categoria::find($id)->update($data)
The answers to this question are wrong about the proper procedure, what you should do is filter the data received by the variable $request, to do so, create an array and capture the fields of interest.
This is the basics, I personally would include several other validations, I foresee many things when dealing with security, but it should be enough for you to update without major problems:
use Illuminate\Support\Facades\Auth; use App\User;
/**
* This is just a demo, modify it according to your needs, include Facades\Auth in the header of the controler to search for the logged in user (Auth::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)
{
$use = Auth::user()->name;
$user = User::where([['id', $id], ['name', $use]]);
$request->validate([
'name'=>'required',
'email'=>'required'
]);
$array = array(
'name' => $request->get('name'),
'email' => $request->get('email')
);
$user->update($array);
return redirect()->route('home')->with('success','Update successfully');
}
I disagree with accepted answer.
From my point of view it is better to use form model binding with array as name attribute (see How to use Laravel form model binding with array as name attribute?).
{{ Form::model(['user' => $user], array('class'=>'form-horizontal')) }}
{{ Form::label('user[email]', 'Email Address') }}
{{ Form::text('user[email]') }}
{{ Form::close() }}
In the controller you can access user data with the following code without bothering about other data transmitted on submit (eg. _method, _token, submit, ...):
$request->input('user');
If you want to use this approach, then you also have to update validation code.
Form model binding in Rails (the other framework I work with) has a far better implementation, the presented approach is the default.

Categories