I want to know how can I have multiple image in my posts?
Currently I have ImageController which I tried to get images and attach to post_id but the issue of that is if I use that method because I still didn't save my post there will be no id to be attached to images.
Any idea on that?
Please take a look for better understanding:
https://ibb.co/huC1Qw
blade:
<form action="upload" id="upload" enctype="multipart/form-data" method="post">
<div class="row">
<div class="col-md-6"><input type="file" class="form-control" name="files[]" multiple></div>
<div class="col-md-6"><input type="submit" class="btn btn-success" value="Upload now"></div>
</div>
</form>
controller:
public function upload(Request $request) {
$files = $request->file('file');
if (!empty($files)):
foreach($files as $file):
Storage::put($file->getClientOriginalName(), file_get_contents($file));
endforeach
endif;
return \response::json(array('success' => true));
}
route:
Route::post('/upload', 'ImageController#upload');
Approach 1.
Return $request->photos or put them in the session while you are not done yet with post submitting. After it was submitted assign references.
Approach 2.
First, save them in [temp] then move and assign to the post.
Approach 3.
Create a default record in your database, assign images to that record, get the record_id post_id and return to the form that post_id. Then just populate that post with your post_id.
Approach 4.
It is not the good choice to save images in the database, just save them as file and place de reference link in the database, or find them by the id of the folder that has the same id as your post, or beautify links to them ... definitely not by saving them to database. It is my opinion, everyone has to find his/her way for an easy living.
Try this :-
use App\ProductsPhoto; \\ add in top of controller
public function upload(Request $request) {
$product = Product::create($request->all());
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$productsPhotos = new ProductsPhoto;
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$destinationPath = 'images/ProductsPhotos'.'/';
$file->move($destinationPath, $fileName);
$productsPhotos->product_id = $product->id,
$productsPhotos->filename = $fileName;
$productsPhotos->save();
}
}
return 'Upload successful!';
}
Hope it helps!
For upload and display images
if you are using two tables.
upload.blade.php
<form method="post" action="{{ url('/uploads') }}" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" class="inputfile" value="{{ old('arquivo') }}" multiple />
Controller
public function show() {
$images = DB::select('SELECT * FROM table1 INNER JOIN table2 on table1.id = table2.id_file');
return view('index')->with('images', $images);
}
public function upload(yourRequest $request) {
$images = model1::create($request->all());
foreach ($request->files as $file) {
$filename = $file->store('/uploads');
modelFiles::create([
'id_file' => $images->id,
'file' => $filename
]);
}
return redirect()->action('Controller#show')->withInput(Request::only('name'));
}
index.blade.php
#foreach($images as $i)
<div class="item {{ $loop->first ? 'active' : '' }}">
<img src="{{ asset("storage/$i->file") }}" alt="...">
</div>
#endforeach
Related
I'm new to Laravel and trying to add Product under Category but when I add Product then it shows this error:
SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into products ..."
Initially i was adding these products without under any category than it was working and now its not adding under Category.
can anyone would prefer to provide me its solution?
here is my form:
<form enctype="multipart/form-data" class="form-horizontal" method="post" action="{{ url('admin/add-product') }}" name="add_product" id="add_product" novalidate="novalidate">{{ csrf_field() }}
<div class="control-group">
<label class="control-label">Under Category</label>
<div class="controls">
<select name="category_id" id="category_id" style="width:220px;">
<?php echo $categories_drop_down; ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Product Name</label>
<div class="controls">
<input type="text" name="product_name" id="product_name">
</div>
</div>
<div class="uploader" id="uniform-undefined"><input name="image" id="image" type="file" size="19" style="opacity: 0;"><span class="filename">No file selected</span><span class="action">Choose File</span></div>
div class="form-actions">
<input type="submit" value="Add Product" class="btn btn-success">
</div>
</form>
here is ProductsController:
ProductsController.php
public function addProduct(Request $request)
{
if ($request->isMethod('post'))
{
$data = $request->all();
$product = new Product;
$product->product_name = $data['product_name'];
$product->product_code = $data['product_code'];
$product->product_color = $data['product_color'];
if ( ! empty($data['description']))
{
$product->description = $data['description'];
}
else
{
$product->description = '';
}
$product->price = $data['price'];
// Upload Image
if ($request->hasFile('image'))
{
$image_tmp = Input::file('image');
if ($image_tmp->isValid())
{
$extension = $image_tmp->getClientOriginalExtension();
$filename = rand(111, 99999) . '.' . $extension;
$large_image_path = 'images/backend_images/products/large/' . $filename;
$medium_image_path = 'images/backend_images/products/medium/' . $filename;
$small_image_path = 'images/backend_images/products/small/' . $filename;
// Resize Images
Image::make($image_tmp)->save($large_image_path);
Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
// Store image name in products table
$product->image = $filename;
}
}
$product->save();
/*return redirect()->back()->with('flash_message_success','Product has been added successfully!');*/
return redirect('/admin/view-products')->with('flash_message_success', 'Product has been added successfully!');
}
$categories = Category::where(['parent_id' => 0])->get();
$categories_drop_down = "<option value='' selected disabled>Select</option>";
foreach ($categories as $cat)
{
$categories_drop_down .= "<option value='" . $cat->id . "'>" . $cat->name . "</option>";
$sub_categories = Category::where(['parent_id' => $cat->id])->get();
foreach ($sub_categories as $sub_cat)
{
$categories_drop_down .= "<option value='" . $sub_cat->id . "'> -- " . $sub_cat->name . "</option>";
}
}
return view('admin.products.add_product')->with(compact('categories_drop_down'));
}
Although, there would be better ways to write this problem, the immediate solution would be to set the category_id field of your Product.
$product->product_name = $data['product_name'];
$product->product_code = $data['product_code'];
$product->product_color = $data['product_color'];
// Add this:
$product->category_id = $data['category_id'];
The main problem you have here is that in your migration you have category_id is not nullable which means it should have a value assigned to it from the controller you can either assign a value for it from your controller or you can go to your migration file and add this line
$table->integer('catagory_id')->nullable();
Then you will remigrate the table and it shouldn't throw this error again, but I prefer that you assign a value for it if you have relationship or something you want to connect it to it but if you don't have relationships then the entire category_id is useless in my point of view
If you want to assign a value to it, you should do something like this in your controller after the new product line:
$product->category_id = $request->input('category_id');
because your controller didn't take the value of the input which has the name of
category_id
As the error implies, it does not have a default value, you could solve it by either create a migration (or revise the one you had) so the column 'category_id' is nullable or just add the following line in the product creation:
$product->category_id = NULL;
You may find more information if needed about nullable at Laravel migration documentation
I'm trying to import my excel to my database but the problem is that theres an error saying "Undefined index: title" referring to the title in the controller.
So this is my code for my controller
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader){
})->get();
if(!empty($insert)){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
print_r('Insert Record succesfully');
}
}
}
return back();
}
And this is for my view blade:
#extends('layouts.app')
#section('content')
<div class="container">
<button class="btn btn-success">Download Excel xls</button>
<button class="btn btn-success">Download Excel xlsx</button>
<button class="btn btn-success">Download CSV</button>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="import_file" />
<button class="btn btn-primary">Import File</button>
</form>
</div>
#endsection
Here is the image of the excel i want to upload to my database. It's an xlsx that i want to upload.
See picture for reference
But the error says like this Error message screenshot
You can insert the sheet data directly by calling the toArray method of the Maatwebsite\Excel\Readers\LaravelExcelReader.
$loadedFile = Excel::load($path);
$inserts = $loadedFile->toArray();
if (!empty($insert)) {
DB::table('items')->insert($insert);
print_r('Inserted Record successfully');
}
However, going by your implementation it should be noted that when a callback is specified for the reader, $reader->all() or $reader->get() returns a Maatwebsite\Excel\Collections\RowCollection or Maatwebsite\Excel\Collections\SheetCollection depending on the amount of sheets the file has.
For your sample where there is a single sheet, you can rightly expect a Maatwebsite\Excel\Collections\RowCollection. Therefore you have
$inserts = [];
Excel::load($path, function($reader) use (&$inserts) {
foreach ($reader->get() as $row) {
$inserts[] = ['title' => $row->title, 'description' => $row->description];
}
});
if (!empty($inserts)) {
DB::table('items')->insert($inserts);
print_r('Inserted Record successfully');
}
been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.
perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$pstoreNum = request('pstoreNum');
$result = perfumes::where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
}
public function perfWeekSearch()
{
$weekNum = request('perfWeekNum');
$result = perfumes::where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
Route::get('/perfumes', 'perfumescontroller#index');
Route::get('/perfumes', 'perfumescontroller#perfWeekSearch');
Blade:
<form action="perfumes" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="perfWeekNum" placeholder="Type in Store Number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
Do i need to use some sort of check if not null method? or is there an easier way??
Thanks
I think this would be work below is your perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$data = $request->all();
if(!empty($data['pstoreNum'])){
$pstoreNum = $data['pstoreNum'];
$result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
} else if(!empty($data['perfWeekNum'])){
$weekNum = $data['perfWeekNum'];
$result = DB::table('perfumes')->where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
}
and you use any with route like below:
Route::any('/perfumes', 'perfumescontroller#index');
I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php
I know, that there are many many cases about this theme already, but I looked them through, and could not find desired. Also I noticed that not a lot of the users got their answer.
I am working with Laravel5, and I'm trying to upload a picture. Simple upload, just save any picture in public/img folder.
I have looked up some tutorials and came up with this code:
View form:
<form action="{{URL::to('adminPanel/addImg/done/'.$projectId)}}" method="get" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And the controller code:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = $id;
$file->move($destinationPath);
}
I keep getting this error :
Call to a member function move() on a non-object
And I am sure, that the chosen file is image.
I would appreciate any help
So its done, the main issue was the POST part! Also the file format, but here are the correct code, that adds the image:
form:
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}"> //this part is to make POST method work
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
controller:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$file->move($destinationPath, $id.'.png');
}
I don't know if you are using Laravel 4.2 or 5.0. But..
I recommend you to use illuminate/html - Form class. Try to use POST instead GET to upload files (https://stackoverflow.com/a/15210810/781251, http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 , http://php.net/manual/en/features.file-upload.post-method.php , http://php.net/manual/en/features.file-upload.php)
If Laravel 4.2:
View:
{{ Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) }}
<label for="file">File</label>
{{ Form::file('file') }}
{{ Form::close() }}
Controller:
public function postImage()
{
if( ( $file = Input::file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return Redirect::back();
}
throw new \Exception('Error while upload file');
}
Laravel 5.0
View:
{!! Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) !!}
<label for="file">File</label>
{!! Form::file('file') !!}
{!! Form::close() !!}
Controller:
public function upload(Request $request)
{
if( ( $file = $request->file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return redirect()->back();
}
throw new \Exception('Error while upload file');
}
To create a file with a new name and keep the extension:
$ext = $file->getClientOriginalExtension();
$newName = str_random(20) . '.' . $ext;
$file->move( storage_path('images') , $newName );
Now, you have a new name with the same extension. To validate if your file is an image or..whatever, use Validator.
Try this
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And get the image as
public function postImage(Request $request) {
$image = $request->file("image");