Uploaded file is not saving to database - laravel

I have created a form where you can upload video files, but I notice that when uploading it, video takes time to upload depending on the size of the file,so to avoid people staring at a screen for a long time waiting for their video to upload I will send them to a page that says "Your video is processing and will be available when ready".The video is indeed saving to the public app folder and also it saves to my aws3 bucket folder as I requested but I noticed that its not saving the file in the database and I don't know why it by passes the database. I am using laravel, ffmpeg to convert and compress videos and ajax. Can someone help me with this. here is my code below
//this the fileupload.blade.php
<div class="container">
<div class="card">
<div class="card-body">
<form method="POST" action="{{ route('fileUploadPost') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input name="file" id="poster" type="file" class="form-control">
<input type="submit" value="Submit" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function validate(formData, jqForm, options) {
var form = jqForm[0];
if (!form.file.value) {
alert('File not found');
return false;
}
}
(function() {
$('form').ajaxForm({
uploadProgress: function(event, position, total, percentComplete) {
window.location.href = "complete";
},
success: function() {
},
complete: function(xhr) {
}
});
})();
</script>
//this is the controller
$request->validate([
'file' => 'required',
]);
$viddy=new Video;
$file = $request->file('file');
$fileName =uniqid().$file->getClientOriginalName();
$request->file->move(public_path('/app'), $fileName);
$name_file=uniqid().'video.mp4';
$ffp=FFMpeg::fromDisk('local')
->open($fileName)
->addFilter(function ($filters) {
$filters->resize(new \FFMpeg\Coordinate\Dimension(640, 480));
})
->export()
->toDisk('s3')
->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame'))
->save($name_file);
$imageName = Storage::disk('s3')->url($name_file);
$viddy->title=$imageName;
$viddy->save();
return response()->json(['success'=>'You have successfully upload file.']);
}

Related

On drop anywhere on body start upload

I currently have a dropzone js area like so
<form method="post"
class="dropzone bg-black"
enctype="multipart/form-data"
action="/">
<br>
<div class="normal-form">
<div class="btn d-inline-block btn-previous">
<input class="btn"
id="files"
type="file"
name="image"
multiple="multiple">
</div>
<button class="btn"
style="font-size: 20px;"
type="submit">Upload
</button>
</div>
</form>
And my dropzone js configuration looks like so
<script defer>
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
autoProcessQueue: false
});
myDropzone.on('drop', function (e) {
document.querySelector('#files').files = e.dataTransfer.files;
});
$('form').on('drop', function () {
$('form').submit();
});
$('form').on('submit', function () {
$('form').addClass('hidden');
$('.loader').removeClass('hidden');
});
</script>
As it works, when some one drops a file or files, it hides, shows a upload gif while it uploads the files till uploaded then redirects.
This works fine. The only issue I'm confused about is how do I make it so if they drop anywhere on the body instead of just the dropzone class, to have that work?
I tried doing
var myDropzone = new Dropzone(document.body, {
autoProcessQueue: false
});
but I get
Uncaught Error: No URL provided.
Any help would be appreciated.
Got it, I had to put in the Dropzone config the url action
var myDropzone = new Dropzone(document.body, {
url: "/",
autoProcessQueue: false,
createImageThumbnails: false,
});

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

How to include new component in axios response

I have an component with text input. After fill input and submit form i sand axios query and after response i need stay on the same page with error popup or include new component with response data.
my component
<template>
<div class="col-md-12">
<div class="form-container">
<form v-on:submit="prepareCollage()" class="main-form">
<div class="form-group">
<input type="hidden" name="_token" value="">
<input placeholder="your text" v-model="text" name="query" type="text" class="form-control">
</div>
<button class="go btn btn-primary">Go!</button>
</form>
</div>
</div>
</template>
<script>
export default {
data () {
return {
text : '',
}
},
methods: {
prepareCollage(){
event.preventDefault();
axios.get('/api/prepare?query='+encodeURIComponent(this.text))
.then(function(result){
const result_data = result.data;
// if controller gave an error
if(result_data.error === true){
let error_text = result_data.error_text;
if(typeof(result_data.with_link) != 'undefined' && result_data.with_link.length > 0){
error_text += "<a href='"+result_data.with_link+"'>"+result_data.link_text+"</a>";
}
Vue.swal({
title: 'Error!',
html: error_text,
type: 'error',
})
}else{
// here i need include new component
}
});
}
}
}
</script>
in "else" block i have to include new vue component with data from this component. I have never used vuejs and have difficulty with understand this.

laravel login via ajax

Im trying to do the login in laravel via ajax so I want this function to return only json object in case of errors
the function returns json only when a input (email or password is empty) , but I insert wrong data in bought of theme the function returns a html page with errors include; but I want to return only these errors without html page (I assume that it it dose return response()->back()->withErrors('errors') )
my Js code :
$('#form-login').submit(function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
email : $('#login_email').val(),
password : $('#login_password').val(),
}
$.ajax({
url: '/login',
type: 'post',
data: data,
success:function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('Content-Type').includes('json')) {
window.location.reload();
}
},
error:function(data) {
// console.log(data['email'])
// console.log(data.email)
if(data.responseJSON.email){
$('#Email-help-block').html(data.responseJSON.email[0])
}else{
$('#Email-help-block').html('')
}
if(data.responseJSON.password){
$('#Password-help-block').html(data.responseJSON.password[0])
}else{
$('#Password-help-block').html('')
}
},
})
});
the function login :
public function login(Request $request)
{
$this->validateLogin($request); // this is where it returns errors
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
My solution to this problem is:
<body>
<main class="container small">
<div class="middle">
<body>
<main class="container small">
<div class="middle">
<img
<br>
<div class="error valign-wrapper" style=" border: 2px solid red; border-radius: 7px;" hidden>
<h5 class="center-align"> Helaas zijn uw inloggegevens incorrect </h5>
</div>
<form method="POST" action="/api/v1/login" class="login">
{!! csrf_field() !!}
<input type="text" name="email" class="emailaddress" placeholder="Je e-mailadres..." style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII="); cursor: auto;" autocomplete="off">
<input type="password" name="password" class="password" placeholder="Je wachtwoord..." style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII="); cursor: auto;" autocomplete="off">
<div class="left">
Wachtwoord vergeten?
← Terug
</div>
<div class="right">
<input type="submit" class="button" value="Log in">
</div>
</form>
</div>
</main>
</body>
#include('footer')
#push('scripts')
<script>
$('form.login').submit(function(e) {
$form = $(this);
e.preventDefault();
$.post(window.location.origin + $form.attr('action'), $form.serialize())
.done(function(data) {
window.location.href = 'account';
})
.fail(function() {
$('.error').show();
});
});
</script>
#endpush
This is html with the error hidden (or you could show it with just ajax) on error. My javascript is pushed to a javascript stack at the bottom.

How to use cashier package in laravel 5.2?

I am creating a user subscription plan, For this I am using cashier package in laravel 5.2. I am following the exact way in provided in the tutorial given in laravel document https://laravel.com/docs/5.2/billing. But I am getting the error
ErrorException in FacebookScraperController.php line 1767:
Undefined variable: creditCardToken
my controller code:
$user = User::find(2);
$res = $user->newSubscription('main', 'monthly')->create($creditCardToken);
dd($res);
What should I pass the value inside the $creditCardToken variable.
I tried to give the card details inside this variable. But getting error.
Please help me out.
You will need to pass the subscription plan here with the token generated at the time of card entry.
Here is the step you can follow.
create a view page:
<form action="/subscription" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_TSGgkchoa9iQU4ZQ628a8Auz');
</script>
<script>
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
and in your controller:
public function subscription(Request $request)
{
$user = User::find(1);
$creditCardToken = $request->stripeToken;
$res = $user->newSubscription('main', 'pro')
->trialDays(30)
->create($creditCardToken, [
'plan' => 'pro',
'email' => $user->email,
]);
}

Resources