Laravel - Uploading Arrays of Image and Video - php

I want to upload an Image and a Video, here is my logic but it seems does not work It only uploads one image. how can i upload 2 separate data. Please Guide me I am new to Laravel thank you
Here is the View which has a form I've used in Form Collectives
Here is where the arrays have been called
My View
{!! Form::open(['action'=>'Admin\PaxSafetyController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{ Form::file('paxsafety_image[]') }} <strong>Upload Image</strong>
<br><br>
{{ Form::file('paxsafety_video[]') }} <strong>Upload Video</strong>
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
My Controller
public function create()
{
$this->validate($request, [
'paxsafety_image' => 'required',
'paxsafety_video' => 'required'
]);
if ($request->has('paxsafety_image'))
{
//Handle File Upload
$paxSafety = [];
foreach ($request->file('paxsafety_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/paxsafety_folder',$fileNameToStore);
array_push($paxSafety, $fileNameToStore);
}
$fileNameToStore = serialize($paxSafety);
}
foreach ($paxSafety as $key => $value) {
$paxSafetyContent = new PaxSafety;
$paxSafetyContent->paxsafety_image = $value;
$paxSafetyContent->save();
}
return redirect('/admin/airlineplus/inflightmagazines/create')->with('success', 'Inflight Magazine Content Inserted');
}

Related

Upload videos in Laravel project

I am having trouble when I try to upload video/movie to my site. It doesn't save the video in the database, but it makes a folder 'movie' in my files with that video in it like it's supposed to. Also I edited my php.ini file for size requirements and session that I made says that it uploaded. Here is my code
View:
<div class="col-md-6">
{!! Form::open(['method'=>'POST', 'action'=> 'MovieController#store', 'files' => true]) !!}
<div class="form-group">
{!! Form::label('movie_name', 'Enter Movie Name:') !!} <br>
{!! Form::text('movie_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('uploaded_path', 'Select Movie:') !!} <br>
{!! Form::file('uploaded_path', null, ['class'=>'form-control'])!!}
</div>
</div>
<div class="form-group">
{!! Form::label('actor_id', 'Actors:') !!}
{!! Form::select('actor_id[]', $actors, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id[]', $categories, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
MovieRequest:
public function rules()
{
return [
'movie_name' => 'required|max:255',
'uploaded_path' => 'mimetypes:video/avi,video/mpeg,video/mp4|required'
];
}
Controller:
public function store(MovieRequest $request)
{
DB::beginTransaction();
try {
if ($request->hasFile('uploaded_path')) {
$filenameWithExt = $request->file('uploaded_path')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('uploaded_path')->getClientOriginalExtension();
$fileNameToStore = $filename. '_'.time().'.'.$extension;
$path = $request->file('uploaded_path')->storeAs('public/movies/', $fileNameToStore);
} else {
$fileNameToStore = 'novideo.mp4';
}
$movie = new Movie;
$movie->movie_name = $request->input('movie_name');
$movie->uploaded_path = $fileNameToStore;
$movie->actors()->attach($request->input('actor_id'));
$movie->categories()->attach($request->input('category_id'));
$movie->save();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
}
Session::flash('success', 'A movie was successfully UPLOADED in the database!');
return redirect()->route('movies.index');
}
Don’t forget to add:
enctype="multipart/form-data"
to movie field.

Laravel - Insert Dynamic Images Arrays JQuery on Database in One Column

I need to store my images in the database in one column dynamically I have no idea how to do it please help me. thank you in advance here is my view controller and model. Here is an image, Below there are an array that on Choose File Button. I want to store them into the database in a column how to do that?
My Database Table name is InflightMagazine
My VIEW code
{!! Form::open(['action'=>'Admin\InflightMagazines#store', 'method' => 'POST','enctype'=>'multipart/form-data']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr class="form-row">
<td> <b>{{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}}</b><br>
{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}
{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle add', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
AJAX / JQuery Code
<script>
$(document).ready(function() {
var len = $('.form-row').length;
$(document).on('click', '.add', function() {
$('#dynamic_field').append('<tr class="form-row" data-id="'+len+'"><td> {{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}} <br> {{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }} {{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}</td><td><button type="button" name="remove" class="btn btn-danger fa fa-minus-circle btn_remove_all"></button></td></tr>');
});
$(document).on('click', '.submit', function() {
$.ajax({
method: "POST",
data: $('#add_name').serialize(),
success: function(data) {
alert(data);
$('#add_name')[0].reset();
}
});
});
$(document).on('click', '.addFile', function() {
var id = $(this).closest('.form-row').data('id');
var elem = '<tr class="'+id+'"><td>{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}<button type="button" name="remove" class="btn btn-danger btn_remove fa fa-minus-circle"></button></td></tr>';
$(elem).insertAfter($(this).closest('tr'));
});
$(document).on('click', '.btn_remove, .btn_remove_all', function() {
if($(this).hasClass('btn_remove_all')){
var id = $(this).closest('.form-row').data('id');
$('tr.'+id).remove();
}
$(this).closest('tr').remove();
});
});
</script>
Controller Storing Function code
public function store(Request $request){
$this->validate($request, [
'inflightmagz_date' => 'required',
'infightmagazine_pdf' => 'required'
]);
if ($request->has('infightmagazine_pdf')){
//Handle File Upload
$inflightmags = [];
foreach ($request->file('infightmagazine_pdf') as $key => $file){
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
}
$fileNameToStore = serialize($inflightmags);
}
}
I think what you are looking for is attribute casting to array
https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
this will allow you to save an array of file locations to a single field in the DB and retrieve them as an array
I would remove the serialise on the $fileNamesToStore
Hope this helps

How to submit files in Laravel

My form is as follow
{{ Form::open(array( 'enctype' => 'multipart/form-data'))}}
<div class="vendor-box-wrap">
<div class="page3-suggested-cat-wrap" style="float: left;width: 100%;border-bottom: 1px dotted;padding-bottom: 10px;margin-left: 20px;">
<label style="width:9%;" for="9009" class="page3-suggested-cat-label" >BoQ</label>
<div class="input-group" style="margin-top: 10px;
width: 70%;">
<span class="form-control"></span>
<span class="input-group-btn">
<span class="btn btn-primary" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
<input name="file|90009|107" id="file|9009"
value="" onchange="$(this).parent().parent().find('.form-control').html($(this).val().split(/[\\|/]/).pop());"
style="display: none;" type="file">
</span>
</div>
</br> <center><h2><strong>OR</strong></h2></center>
</div>
</div>
<div class="next-btn-wrap"><div class="cf"></div>
<div class="back-btn-wrap">
{{ Form::submit('Back',array('class' => 'back-btn', 'name' => 'back'))}}
</div>
<div class="save-btn-wrap">
{{ Form::submit('Save',array('class' => 'save-btn','name' => 'save'))}}
</div>
{{ Form::submit('Next',array('class' => 'next-btn','name' => 'next'))}}
</div>
{{ Form::close()}}
and in my controller I am using following code to get the data
$aa = Input::except(array('_token','back','save','next'));
//dd($aa);
foreach ($aa as $key=>$value){
$ids = explode("|",$key);
if(isset($ids[0]) && $ids[0]=="file" ){
$userid = Session::get('userid');
$event = Session::get('event');
$fileTblObj = new fileHandler();
$ans = Answer::find($ids[2]);
if(isset($aa[$key])){
//dd($aa[$key]);
if(Input::file($key)->isValid()) {
$destinationPath = 'app/uploads/'.$event.'/'.$userid.'/'.$pageNo ; // upload path
$extension = Input::file($key)->getClientOriginalExtension(); // getting image extension
$name = Input::file($key)->getClientOriginalName();
$curFilesize = Input::file($key)->getClientSize();
$mime =Input::file($key)->getMimeType();
if (!File::exists($destinationPath."/boq-".$name)){
//creating details for saving inthe file_handler Table
$fileTblObj->user_id = $userid;
$fileTblObj->eventName = $event ;
$fileTblObj->fileName = "boq-".$name;
$fileTblObj->formPage =$pageNo ;
$fileTblObj->filePath = $destinationPath."/";
$fileTblObj->mime= $mime;
$ans->answer_text = 'Yes';
Input::file($key)->move($destinationPath, "boq-".$name); // uploading file to given path
//Input::file($key)->move($boqPath, $boqname); // uploading file to given path
//Save filedetails
$fileTblObj->save();
$ans->save();
Session::flash('success', 'Upload successfully');
}else if(File::size($destinationPath."/".$name) != $curFilesize){
$fileDtls = $fileTblObj->where('uid',$userid)->where('fileName',$name)->where('formPage',$pageNo)->first();
Input::file($key)->move($destinationPath, $name);
$ans->answer_text = 'Yes';
$ans->save();
$fileTblObj->where('id',$fileDtls->id)->update(array('updated_at'=>date("Y-m-d h:m:s",time())));
}
//return Redirect::to('upload');
}
}
else
{
if($ans->answer_text =='')
{
$ans->answer_text = 'No';
$ans->save();
}
}
}
My problem is I am not able to get the file details on the back-end
the if statement
if(isset($ids[0]) && $ids[0]=="file" ){
}
is always false .
Any Idea How I can fix this. I also tried changing the The FOrm function to
{{ Form::open(array('files' => true)) }}
Still its not showing the file details
To send a file, I personally use this methods.
View:
{!! Form::open(array('action' => 'TestController#store', 'method' => 'POST', 'files'=>true)) !!}
{!! Form::file('thefile') !!}
{!! Form::submit('Save', array('class' => 'btn')) !!}
{!! Form::close() !!}
Controller:
$thefile = Input::file('thefile');
Hope this helps!

validate uploading image on laravel 4

I'm new to Laravel. I have a form with a File upload function on it. How can I validate image file? . when i execute my code the images are getting uploaded but URL is not saved to the MySQL database, and it shows validation errors on the form as follows.
The thumbnail must be an image.
The large image must be an image.
Here's my input and validation code .
{{ Form::open(array('url' => 'admin/templates/save', 'files' => true, 'method' => 'post')) }}
#if($errors->has())
#foreach($errors->all() as $error)
<div data-alert class="alert-box warning round">
{{$error}}
×
</div>
#endforeach
#endif
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('title','Title:') }}
{{ Form::text('title',Input::old('title')) }}
</div>
</div>
<div class="row">
<div class="small-7 large-7 column">
{{ Form::label('description','Description:') }}
{{ Form::textarea('description',Input::old('description'),['rows'=>5]) }}
</div>
</div>
<div class="row">
<div class="small-7 large-7 column">
{{ Form::label('detailed_description','Detailed description:') }}
{{ Form::textarea('detailed_description',Input::old('detailed_description'),['rows'=>5]) }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('thumbnail','Choose thumbnail image:') }}
{{ Form::file('thumbnail') }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('large_image','Choose large image:') }}
{{ Form::file('large_image') }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('targeturl','Target URL:') }}
{{ Form::text('targeturl',Input::old('Target URL')) }}
</div>
</div>
{{ Form::submit('Save',['class'=>'button tiny radius']) }}
{{ Form::close() }}
Controller code
<?php
class TemplateController extends BaseController
{
public function newTemplate()
{
$this->layout->title = 'New Template';
$this->layout->main = View::make('dash')->nest('content', 'templates.new');
}
public function saveTemplate() {
//TODO - Validation
$destinationPath = '';
$filename = '';
$destinationThumb = '';
$thumbname = '';
$thumb = Input::file('thumbnail');
$destinationThumb = public_path().'/thumb/';
$thumbname = str_random(6) . '_' . $thumb->getClientOriginalName();
$uploadSuccess = $thumb->move($destinationThumb, $thumbname);
$file = Input::file('large_image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$rules = [
'title' => 'required',
'description' => 'required',
'detailed_description' => 'required',
'targeturl' => 'required',
'thumbnail' => 'required|image',
'large_image' => 'required|image'
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes()) {
$template = new Template();
$template->title = Input::get('title');
$template->description = Input::get('description');
$template->thunbnailURL = $destinationThumb . $thumbname;
$template->detailedDescription = Input::get('detailed_description');
$template->targetURL = Input::get('targeturl');
$template->detailImageURL = $destinationPath . $filename;
//$user->created_at = DB::raw('NOW()');
//$user->updated_at = DB::raw('NOW()');
$template->save();
return Redirect::back()->with('success', 'Template added!');
} else
return Redirect::back()->withErrors($validator)->withInput();
}
}
Please help me.
Move your upload code inside validation passes
public function saveTemplate() {
//TODO - Validation
$rules = [
'title' => 'required',
'description' => 'required',
'detailed_description' => 'required',
'targeturl' => 'required',
'thumbnail' => 'required|image',
'large_image' => 'required|image'
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes()) {
$thumb = Input::file('thumbnail');
$destinationThumb = public_path().'/thumb/';
$thumbname = str_random(6) . '_' . $thumb->getClientOriginalName();
$uploadSuccess = $thumb->move($destinationThumb, $thumbname);
$file = Input::file('large_image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$template = new Template();
$template->title = Input::get('title');
$template->description = Input::get('description');
$template->thunbnailURL = $destinationThumb . $thumbname;
$template->detailedDescription = Input::get('detailed_description');
$template->targetURL = Input::get('targeturl');
$template->detailImageURL = $destinationPath . $filename;
//$user->created_at = DB::raw('NOW()');
//$user->updated_at = DB::raw('NOW()');
$template->save();
return Redirect::back()->with('success', 'Template added!');
} else
return Redirect::back()->withErrors($validator)->withInput();
}

Laravel 4: moving files once uploaded

Im having problems trying to upload photos and any kind of file on my app, because the do upload but as .tmp files and they dont display properly on my view
1.-My form,Im trying to upload a member with name, group, email, description and a photo
{{Form::open(array('action' => 'AdminController#addMember','files'=>true)) }}
{{ Form::label('file','Agregar Imagen',array('id'=>'','class'=>'')) }}
{{ Form::file('file','',array('id'=>'','class'=>'')) }}
<br/>
{{Form::text('name','',array('class' => 'form-control','placeholder'=> 'Nombre'))}}
{{Form::text('group','',array('class' => 'form-control','placeholder'=> 'Cargo'))}}
{{Form::text('email','',array('class' => 'form-control','placeholder'=> 'Correo'))}}
{{Form::textarea('description','',array('class' => 'form-control','placeholder'=>''))}}
<!-- submit buttons -->
{{ Form::submit('Guardar') }}
<!-- reset buttons -->
{{ Form::reset('Reset') }}
{{ Form::close() }}
2.-My upload function in the controller
public function addMember()
{
$name = Input::file('file')->getClientOriginalName();
$newname = Input::file('file')->getFilename();
Input::file('file')->move(storage_path(),$name);
$subpath = storage_path();
$path = $subpath.'/'.$newname2;
$name2 = Input::get('name');
$email = Input::get('email');
$description = Input::get('description');
$group = Input::get('group');
DB::table('contactgroups')->insert(
array('group' => $group, 'name' => $name2, 'path' => $path, 'email' => $email, 'description' => $description)
);
$members = DB::table('contactgroups')->get();
return View::make('admin.members',['members' => $members]);
}
I know i should be using a Model to upload things on my database but that's not the problem right now
3.- My display view
#extends('layouts.main')
#section('content')
#foreach($members as $member)
<div class = "row fondue">
<h3><div class="col-md-12"><b><?=$member->name ?></b></div></h3>
<div class="col-md-4"> <img src="<?=$member->path ?>" alt="Image" class = "contact-img"></div>
<div class="col-md-4"><?=$member->description ?></div>
<div class="col-md-4"><?=$member->email ?></div>
</div>
#endforeach
#stop
and that's all...the info is saved in the database but the images are not showing properly on the view and, the files are uploaded as tmp files i dont know why
From the Laravel documentation
Moving An Uploaded File
Input::file('photo')->move($destinationPath);
Input::file('photo')->move($destinationPath, $fileName);
Source: http://laravel.com/docs/4.2/requests#files

Categories