Mistake in validation in Laravel - php

Something is wrong with my validation. Data from the form is created and I can see it when I use the dd() function. But when it comes to creating and sending that data to the database it creates an empty row. My Laravel version is 8.83.17. Here's my route:
Route::middleware(['auth.amicms'])->name('amicms.')->prefix('amicms')->group(function() {
Route::resource('/posts', PostController::class);
});
Here's the request:
public function rules()
{
return [
'name_en' => 'required',
'body_en' => 'required',
'name_ua' => 'required',
'body_ua' => 'required',
'name_ru' => 'required',
'body_ru' => 'required',
'meta_title_en' => 'string',
'meta_description_en' => 'string',
'meta_keywords_en' => 'string',
'meta_title_ua' => 'string',
'meta_description_ua' => 'string',
'meta_keywords_ua' => 'string',
'meta_title_ru' => 'string',
'meta_description_ru' => 'string',
'meta_keywords_ru' => 'string',
'image' => 'required|image',
'price' => 'required',
'status' => 'required'
];
}
Here's the model:
protected $fillable = ['name_en, body_en, name_ua, body_ua, name_ru, body_ru,
meta_title_en, meta_description_en, meta_keywords_en, meta_title_ua, meta_description_ua, meta_keywords_ua,
meta_title_ru, meta_description_ru, meta_keywords_ru, image, price, status'];
Here's the controller
public function store(StorePostRequest $request)
{
$input = $request->all();
if ($image = $request->file('image')) {
$imageDestinationPath = 'uploads/';
$postImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($imageDestinationPath, $postImage);
$input['image'] = "$postImage";
}
Post::create($input);
return view ('amicms.posts.index', ['layout' => $this->layout]);
}
Here's the view:
form action="{{ route('amicms.posts.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Языковая версия</label>
<select id="language" class="custom-select"
name="language" required>
<option value="ru">Русский</option>
<option value="ua">Украинский</option>
<option value="en">English</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Статус</label>
<select class="custom-select #if($errors->has('status')) noty_type_error #endif"
name="status" id="" required>
<option value="1">Published</option>
<option value="0">Not Published</option>
</select>
</div>
</div>
</div>
#php($formLang = ['ru', 'ua', 'en'])
#for($i=0; $i<3;$i++)
<div id="build-form-{{ $formLang[$i] }}" class="d-none">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Name (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="name_{{ $formLang[$i] }}" type="text" placeholder=""
class="form-control #if($errors->has('name_ru')) noty_type_error #endif">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Full description of the entry (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<textarea class="form-control #if($errors->has('body')) noty_type_error #endif"
name="body_{{ $formLang[$i] }}" id="summernote"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Meta Title (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_title_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Meta Keywords (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_keywords_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Meta Description (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_description_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
#endfor
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Photo</label>
<input name="image" type="file" placeholder="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Price</label>
<input name="price" type="number" placeholder="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="text-right mrg-top-5">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</form>
Here's the migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name_en')->nullable();
$table->text('body_en')->nullable();
$table->string('name_ru')->nullable();
$table->text('body_ru')->nullable();
$table->string('name_ua')->nullable();
$table->text('body_ua')->nullable();
$table->text('meta_title_en')->nullable();
$table->text('meta_description_en')->nullable();
$table->text('meta_keywords_en')->nullable();
$table->text('meta_title_ru')->nullable();
$table->text('meta_description_ru')->nullable();
$table->text('meta_keywords_ru')->nullable();
$table->text('meta_title_ua')->nullable();
$table->text('meta_description_ua')->nullable();
$table->text('meta_keywords_ua')->nullable();
$table->string('image');
$table->decimal('price', 10, 2);
$table->integer('status');
$table->timestamps();
});
}

protected $fillable = [
'name_en','body_en','name_ua','body_ua','name_ru',' body_ru','meta_title_en','meta_description_en','meta_keywords_en','meta_title_ua','meta_description_ua','meta_keywords_ua','meta_title_ru','meta_description_ru','meta_keywords_ru','image','price','status'
];

Related

302 found in Laravel project

Route
Route::get('/addproduct', [UserController::class, 'addproduct'])->name('addproduct');
Route::post('/addnewproduct', [UserController::class, 'addnewproduct'])->name('addnewproduct');
Route::get('/showproducts', [UserController::class, 'showproducts'])->name('showproducts');
Controller
public function addproduct()
{
return view('addProduct');
}
public function addnewproduct(Request $request)
{
$user_id = Auth::user()->id;
$request->validate([
'file' => 'required|mimes:jpg,png,gif,svg',
'name' => 'required|string|min:3|max:30',
'description' => 'required|string|min:1|max:255',
'category' => 'required|string|max:255',
]);
$productModel = new Product();
$filename =time().'_' .$request->name;
$filePath = $request->file('file')->move('upload', $filename);
$productModel->name = $request->name;
$productModel->description = $request->description;
$productModel->category = $request->category;
$productModel->image = $filePath;
$productModel->save();
return redirect()->route('showproducts');
}
public function showproducts()
{
$user_id = Auth::user()->id;
$results=DB::select('SELECT * FROM products');
$data = [
'results' =>$results
];
return view('showProduct')->with($data);
}
View
<div class="card-body">
<form method="POST" action="{{ route('addnewproduct') }}" class="needs-validation form" enctype="multipart/form-data" novalidate>
#csrf
<div class="row">
<div class="col-sm-6">
<input type="file" id="input-file-now" class="form-control dropify" name="file" required/>
</div>
<div class="col-sm-6">
<div class="row mb-3">
<label for="validationName" class="form-label">Product name</label>
<div class="input-group has-validation">
<input type="text" class="form-control" name="name" id="validationName" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
You have to enter Product name!
</div>
</div>
</div>
<div class="row mb-3">
<label for="validationCategory" class="form-label">Category</label>
<div class="input-group has-validation">
<select class="form-select" name="category" id="validationCategory" required>
<option selected disabled value="">Select...</option>
<option value="c1">c1</option>
<option value="c2">c2</option>
</select>
</div>
<div class="invalid-feedback">
Please select Category
</div>
</div>
<div class="row mb-3">
<label for="validationDes" class="form-label">Description</label>
<div class="input-group has-validation">
<textarea type="text" class="form-control text-des" name="address" id="validationDes" aria-describedby="inputGroupPrepend" required></textarea>
<div class="invalid-feedback">
Please enter product descriiption in here.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Check it.
</label>
<div class="invalid-feedback">
You have to checkbox!
</div>
</div>
</div>
<div class="row">
<div class="float-end">
<button class="btn btn-primary sumbtn float-end" type="submit"><i class="bi bi-person-plus-fill"></i> ADD</button>
</div>
</div>
</form>
</div>
after enter all fields and file select and then click checkbox, but when I click button don't go to showproducts page, and don't save enterd data and file.
view screenshot
after click button get 302 and not redirect to "showproducts"
Please help me, I'm very very stress with that problem

undefined offset: 1 when storing data from dynamic form

I'm trying to save data to the database using a dynamic form using javascript, I followed several methods from the internet, but when I try to send data to the database, there is an error undefined offset: 1 in the following line:
'question' => $question[$i], (On controller)
can anyone help me?
here is the form.blade.php
<form action="{{ url('/rating/post-form') }}" method="POST">
#csrf
<div class=" col-sm-12 nopadding form-group">
<label for="survei_tag">Kategori</label>
<input type="text" class="form-control" id="survei_tag" name="survei_tag">
</div>
<div class="col-sm-12 nopadding form-group">
<label for="judul">Judul</label>
<input type="text" class="form-control" id="judul" name="judul">
</div>
<div id="education_fields"></div>
<div class="col-sm-12 nopadding">
<div class="form-group">
<label for="pertanyaan">Pertanyaan</label>
<input type="text" class="form-control" id="question" name="question[]"
placeholder="Tambahkan Pertanyaan">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_1" name="opsi_1[]"
placeholder="Opsi 1">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_2" name="opsi_2[]"
placeholder="Opsi 2">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_3" name="opsi_3[]"
placeholder="Opsi 3">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<div class="form-group">
<input type="text" class="form-control" id="opsi_4" name="opsi_4[]"
placeholder="Opsi 4">
</div>
<div class="input-group-btn">
<button class="btn btn-success" type="button"
onclick="education_fields();">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<button type="submit" class="btn btn-primary pull-right">
Simpan
</button>
</form>
here is the main.js
var room = 1;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + room);
var rdiv = 'removeclass' + room;
divtest.innerHTML = `
<div class="col-sm-12 nopadding">
<div class="form-group">
<label for="question">Pertanyaan</label>
<input type="text" class="form-control" id="question" name="question[]"
placeholder="Tambahkan Pertanyaan">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_1" name="opsi_1[]"
placeholder="Opsi 1">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_2" name="opsi_2[]"
placeholder="Opsi 2">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="opsi_3" name="opsi_3[]"
placeholder="Opsi 3">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<div class="form-group">
<input type="text" class="form-control" id="opsi_4" name="opsi_4[]"
placeholder="Opsi 4">
</div>
<div class="input-group-btn">
<button class="btn btn-danger" type="button" onclick="remove_education_fields(' + room + ');">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
<div class="clear">
</div>
`;
objTo.appendChild(divtest);
}
function remove_education_fields(rid) {
$
('.removeclass' + rid).remove();
}
here is the model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuids;
class questions extends Model
{
use HasFactory,Uuids;
protected $table = 'survei_questions';
public $timestamps = true;
protected $fillable = [
'survei_tag',
'question_number',
'question',
'sq_instansi_id',
'sq_user_id',
'judul',
'opsi_1',
'opsi_2',
'opsi_3',
'opsi_4'
];
}
here is the controller :
public function storeQuestions(Request $request){
$request->validate([
'survei_tag' =>'required|string|max:255',
'judul' => 'required|string',
'question' => 'required|string',
'opsi_1' => 'required|string',
'opsi_2' => 'required|string',
'opsi_3' => 'required|string',
'opsi_4' => 'required|string',
]);
$survei_tag = $request->survei_tag;
$judul = $request->judul;
$question = $request->question;
$opsi_1 = $request->opsi_1;
$opsi_2 = $request->opsi_2;
$opsi_3 = $request->opsi_3;
$opsi_4 = $request->opsi_4;
for ($i = 1; $i <= count($question); $i++) {
$saveData = [
'survei_tag' => $survei_tag,
'question_number' => $i,
'question' => $question[$i],
'sq_instansi_id' => Auth::user()->instansiID,
'sq_user_id' => Auth::id(),
'judul' => $judul,
'opsi_1' => $opsi_1[$i],
'opsi_2' => $opsi_2[$i],
'opsi_3' => $opsi_3[$i],
'opsi_4' => $opsi_4[$i]
];
DB::table('survei_questions')->insert($saveData);
}
return Redirect::to('/rating/create-form')->with('success','Data berhasil disimpan');
}

Form with enctype return null file in request

I tried to edit the products in my store. On request, missing $request->file('image');
I'm attaching the source code below, I really don't know why I don't receive the image in the request, because I think it's correct what I did
My form :
<form method="POST" action="{{ route('products.update', $product->id)}}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput1">Product slug</label>
<input type="text" name="product_slug" value="{{$product->product_slug}}" class="form-control" id="exampleFormControlInput1" placeholder="Enter slug">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput111">Product title</label>
<input type="text" name="product_title" value="{{$product->product_title}}" class="form-control" id="exampleFormControlInput111" placeholder="Enter slug">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput2">Product category</label>
<input type="text" name="product_category" value="{{$product->product_category}}" class="form-control" id="exampleFormControlInput2" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput3">Product brand</label>
<input type="text" name="product_brand" value="{{$product->product_brand}}" class="form-control" id="exampleFormControlInput3" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput22">Product display</label>
<input type="text" name="product_display" value="{{$product->product_display}}" class="form-control" id="exampleFormControlInput22" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput34">Product ram</label>
<input type="text" name="product_ram" value="{{$product->product_ram}}" class="form-control" id="exampleFormControlInput34" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput33">Product os</label>
<input type="text" name="product_os" value="{{$product->product_os}}" class="form-control" id="exampleFormControlInput33" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput333">Product camera</label>
<input type="text" name="product_camera" value="{{$product->product_camera}}" class="form-control" id="exampleFormControlInput333" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput8">Product price</label>
<input type="text" name="product_price" value="{{$product->product_price}}" class="form-control" id="exampleFormControlInput8" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlFile1">Change product photo</label>
<input type="file" name="image" value="{{$product->product_image}}" class="form-control-file" id="exampleFormControlFile1">
<img src="/storage/img/tech/{{$product->product_image}}" style="width:300px" alt="product_image">
</div>
</div>
</div>
<div class="form-group">
<label for="short_description">Short description</label>
<textarea class="form-control" name="about_product" id="short_description" rows="10">{{$product->about_product}}</textarea>
</div>
<div class="form-group">
<label for="long_description">Long description</label>
<textarea class="form-control" name="product_description" id="long_description" rows="10">{{$product->product_description}}</textarea>
</div>
<input type="submit" value="Edit" class="btn btn-success" name="submit">
Go back
</form>
If I remove the part with the image, the code is perfectly functional
My function in controller(type resource)
public function update(Request $request, $id)
{
dd($request->all());
$request->validate([
'product_slug' => 'required|max:100',
'product_title' => 'required|max:100',
'product_category' => 'required|max:100',
'product_brand' => 'required|max:100',
'product_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'product_display' => 'required',
'product_camera' => 'required',
'product_ram' => 'required',
'product_os' => 'required',
'product_price' => 'required|max:100',
'about_product' => 'required',
'product_description' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'storage/img/tech/';
$profileImage = $image->getClientOriginalName();
$image->move($destinationPath, $profileImage);
$input['image'] = $profileImage;
} else {
unset($input['image']);
}
$product = Product::find($id);
$product->product_slug = $request->get('product_slug');
$product->product_title = $request->get('product_title');
$product->product_category = $request->get('product_category');
$product->product_brand = $request->get('product_brand');
$product->product_display = $request->get('product_display');
$product->product_ram = $request->get('product_ram');
$product->product_camera = $request->get('product_camera');
$product->product_os = $request->get('product_os');
$product->product_price = $request->get('product_price');
$product->product_image = $profileImage;
$product->about_product = $request->get('about_product');
$product->product_description = $request->get('product_description');
$product->update();
return redirect('/admin/products')->with('success', "product updated!");
}
The core issue here is that value="{{ $product-> product_image }}" is not valid. <input type="file"> doesn't support that, as the image needs to be directly uploaded from the User's machine, and unless a file is selected and uploaded, $request->file('image') will be null.
To handle this cleaner, use some conditional logic in the Controller:
First, upload the image and set a reference to the file:
$profileImage = null;
if ($image = $request->file('image')) {
$destinationPath = 'storage/img/tech/';
$profileImage = $image->getClientOriginalName();
$image->move($destinationPath, $profileImage);
}
Next, set the $product->product_image based on the value of $profileImage:
$product = Product::find($id);
...
if ($profileImage)
$product->product_image = $profileImage;
}
A ternary or null-coalesce statement can be used, but it'll look a bit weird:
$product->product_image = $profileImage ? $profileImage : $product->product_image;
// OR
$product->product_image = $profileImage ?? $product->product_image;
Both of these cases will set $product->product_image to $profileImage, or the existing value of $product->profile_image if nothing is provided (that will be an existing image or null)

Laravel record not submitting

I have a form in my Laravel 4 web app that is refusing to submit to the database. Each time i try to submit, the page just reloads and i see no error messages even in the laravel log. I have spent two days trying to figure out what the problem is as I can't seem to see anything wrong with the code.
Any help will be appreciated.
/**** THE FORM VIEW ***/
<div class="container">
<div class="row">
#if(Session::has('success'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{Session::get('success')}}
</div>
#elseif(Session::has('fail'))
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{Session::get('fail')}}
</div>
#endif
</div>
#include('partials.admin-navbar')
<div class="admin_profile_content">
<form class="" method="post" action=" {{URL::route('postSubmitCompetition')}}">
<div class="" style="width:80%; margin:auto;">
<div class="panel panel-default">
<div class="panel-heading">Organization </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Select the Organization hosting this competition </label>
<div class="col-sm-10">
{{ Form::select('organization', $organizations, null, ['class' => 'form-control']) }}
<p class="text-danger">
#if($errors->has('organization'))
{{ $errors->first('organization') }}
#endif
</p>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Competition name </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Competition name </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" name="competition_name">
<p class="text-danger">
#if($errors->has('competition_name'))
{{ $errors->first('competition_name') }}
#endif
</p>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Prizes </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label">Total prize pool</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" name="total_prize">
</div>
</div>
<div class="form-group" style="padding-top:41px;">
<label for="" class="col-sm-2 control-label">Number of prize-winning places</label>
<div class="col-sm-1">
Top
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="" name="number_of_winning_places">
<p class="text-danger">
#if($errors->has('number_of_winning_places'))
{{ $errors->first('number_of_winning_places') }}
#endif
</p>
</div>
<div class="col-sm-3">
competitors will win a prize
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Timeline </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label"> Start and end date </label>
<div class="col-sm-3">
<input type="text" class="form-control" id="competition_start_date" name="competition_start_date">
<p class="text-danger">
#if($errors->has('competition_start_date'))
{{ $errors->first('competition_start_date') }}
#endif
</p>
<input type="hidden" name="hidden_start_date" id="hidden_start_date">
</div>
<div class="col-sm-2">
to
</div>
<div class="col-sm-3">
<input type="text" class="form-control" id="competition_end_date" name="competition_end_date">
<p class="text-danger">
#if($errors->has('competition_end_date'))
{{ $errors->first('competition_end_date') }}
#endif
</p>
<input type="hidden" name="hidden_end_date" id="hidden_end_date">
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Competition details </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label"> Competition details </label>
<div class="col-sm-10">
<textarea class="form-control" name="competition_details" id="competition_details" rows="10"> </textarea>
<p class="text-danger">
#if($errors->has('competition_details'))
{{ $errors->first('competition_details') }}
#endif
</p>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Competition Status </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label"> Set competition status </label>
<div class="col-sm-10">
<select class="form-control" name="competition_status" id="competition_status">
<option value="0">Coming Soon</option>
<option value="1">Live </option>
</select>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Competition data </div>
<div class="panel-body">
<div class="form-group">
<label for="" class="col-sm-2 control-label"> Upload the data for the competition </label>
<div class="col-sm-10">
<input type="file" id="competition_data_1" name="competition_data_1">
<p class="help-block"> Data file/folder 1</p>
</div>
</div>
</div>
</div>
{{ Form::token() }}
<div class="panel panel-default">
<div class="panel-heading">Upload Competition </div>
<div class="panel-body">
<div class="form-group">
<div class="col-sm-10">
<input type="submit" class="btn btn-primary btn-lg btn-block" id="submit_competition" value="Submit">
</div>
</div>
</div>
</div>
</div>
</form>
<hr>
/* the controller method */
public function postSubmitCompetition()
{
$validator = Validator::make(Input::all(), array(
'organization' => 'required',
'competition_name' => 'required',
'prize_winning_places' => 'required',
'competition_start_date' => 'required',
'competition_end_date' => 'required',
'competition_details' => 'required',
'status' => 'required'
));
if($validator->fails())
{
return Redirect::route('getSubmitCompetition')->withErrors($validator)->withInput();
}
else
{
$competition = new Competition();
$competition->hosting_organization_id = Input::get('organization');
$competition->competition_name = Input::get('competition_name');
$competition->total_prize_pool = Input::get('total_prize');
$competition->prize_winning_places = Input::get('number_of_winning_places');
$competition->start_date = Input::get('competition_start_date');
$competition->end_date = Input::get('competition_end_date');
$competition->competition_details = Input::get('competition_details');
$competition->status = Input::get('competition_status');
if($competition->save())
{
return Redirect::route('getSubmitCompetition')->with('success', 'You have successfully created this competition');
}
else
{
return Redirect::route('getSubmitCompetition')->with('fail', 'An error occurred while creating that competition. Please contact sys admin');
}
}
}
/* the route */
Route::post('/admin/submit-a-competition', array('uses' => 'CompetitionController#postSubmitCompetition', 'as' => 'postSubmitCompetition'));
Problem
Laravel never saves your data because the validator fails.
$validator = Validator::make(Input::all(), array(
'organization' => 'required',
'competition_name' => 'required',
'prize_winning_places' => 'required',
'competition_start_date' => 'required',
'competition_end_date' => 'required',
'competition_details' => 'required',
'status' => 'required'
));
You require prize_winning_places and status but there are no input fields for these two in the view.
The missing input fields:
Field name: status - Problem: You made a select with the name: competition_status instead of: status
<select class="form-control" name="competition_status" id="competition_status">
<option value="0">Coming Soon</option>
<option value="1">Live </option>
</select>
Field name: prize_winning_places - Problem: You made an input field with the name: ** number_of_winning_places **instead of prize_winning_places
<input type="text" class="form-control" id="" name="number_of_winning_places">
Solution
Change the $validator variable to:
$validator = Validator::make(Input::all(), array(
'organization' => 'required',
'competition_name' => 'required',
'number_of_winning_places' => 'required',
'competition_start_date' => 'required',
'competition_end_date' => 'required',
'competition_details' => 'required',
'competition_status' => 'required'
));
Check this line:
<form class="" method="post" action=" {{URL::route('postSubmitCompetition')}}">
here form action is the route name not the function name. Like:
Route::post('/save_data', array('uses' => 'CompetitionController#postSubmitCompetition', 'as' => 'postSubmitCompetition'));
It will route your route to the function.

Upload images in Codeigniter

I'm new to Codeigniter and I'm having problem with image upload function.
Error says - You did not select a file to upload.
Can anyone check my code and tell me what to do?
THIS IS MY CONTROLLER
This is my Controller which processes data.
public function add_data() {
$this->load->view('admin/header.php');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('price', 'price', 'required');
$this->load->helper(array('form', 'url'));
if ($this->form_validation->run() == TRUE)
{
$this->load->view('admin/add_view.php');
$config['upload_path'] = './files/';
$config['allowed_types'] = 'jpg';
$this->load->library('upload', $config);
$this->upload->do_upload('picture');
$this->upload->data();
$data = array(
'name' => $this->input->post('name'),
'info' => $this->input->post('info'),
'gorod' => $this->input->post('gorod'),
'price' => $this->input->post('price'),
'amount' => $this->input->post('amount'),
'age' => $this->input->post('age'),
'status' => $this->input->post('status'),
'minbal' => $this->input->post('minbal'),
'contacts' => $this->input->post('contacts'),
'email' => $this->input->post('email'),
'alias' => $this->input->post('alias'),
'filename' => $this->input->post('picture')
);
$this->Adminmodel->add_record($data);
}
else
{
$this->load->view('admin/formnotsuccess');
}
}
VIEW
<form method="post" action="add_data" role="form" style="padding: 30px">
<div class="row">
<div class="form-group col-md-6 ">
<label>Название университета</label></br>
<input type="text" name="name" class="form-control" size="20">
</div>
</div>
<div class="row">
<div class="form-group col-md-10">
<label>Информация об университете</label></br>
<textarea id="textarea" name="info"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Город</label></br>
<select class="form-control" id="gorod" name="gorod">
<option value="Алматы">Алматы</option>
<option value="Астана">Астана</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Стоимость обучения</label>
<input type="text" name="price" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Количество студентов</label>
<input type="text" name="amount" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Возраст университета</label>
<input type="text" name="age" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Статус университета</label></br>
<select class="form-control" id="status" name="status">
<option value="Государственный">Государственный</option>
<option value="Частный">Частный</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Минимальный балл для поступления</label>
<input type="text" name="minbal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Контактные данные</label>
<textarea id="textarea2" name="contacts"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>E-mail</label></br>
<input type="text" name="email" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Alias</label></br>
<input type="text" name="alias" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label>Картинка заднего фона</label></br>
<input type="file" name="picture" class="form-control">
</div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
You are missing
enctype="multipart/form-data" in form
Read php file upload
And Upload code should be like bellow. Its easy to track your errors
if(!$this->upload->do_upload()) # do_upload('picture');
{
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
print_r($data);
}

Categories