Laravel - dropbox driver - This driver does not support retrieving URLs - dropbox

Using
Laravel 5.7
I'm trying to use dropbox driver to upload images , it works .. but when i want to get the url .. it gives me an error
This driver does not support retrieving URLs
filesystems.php
'disks' => [
'dropbox' => [
'driver' => 'dropbox',
'app_secret' => env('DROPBOX_APP_SECRET'),
'token' => env('DROPBOX_TOKEN'),
],
],
UploadController.php
public function postUpload(Request $request)
{
$user = Auth::user();
$file = $request->file('picture');
$filename=uniqid($user->id."_").".".$file->getClientOriginalExtension();
Storage::disk('dropbox')->put($filename, File::get($file), 'public');
$url = Storage::disk('dropbox')->url($filename);
$user->profile_pic = $url;
$user->save();
$user->profile_pic = $filename;
$user->save();
return view('upload-complete')->with('filename', $filename)->with('url',$url);
}
upload-complete.blade.php
#extends('template')
#section('content')
<div class="container">
<h1>File Uploaded</h1>
<hr />
<div class="text-center">
<img src="{{ $url }}" class="img-rounded" />
</div>
</div>
#endsection

Related

I cannot get the uploaded file returned using codeignter3 fileupload()

I have the following code for file upload in the corresponding model file of codeigniter3.
$config['upload_path'] = './assets/img/report/';
$config['allowed_types'] = 'txt|odt|jpg|png|jpeg|pdf|docx';
$config['file_name'] = $this->id;
$config['overwrite'] = true;
$config['max_size'] = '150000';
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')) {
return $this->upload->data('file_name');
}
return default.jpg;
The corresponding view file has the following code
<div class="form-group">
<label for="file">Attachment</label>
<input class="form-control-file"
type="file" name="file" />
<div class="invalid-feedback">
<?php echo form_error('file') ?>
</div>
</div>
But the code always returns default.jpg. How can I fix to return the uploaded file correctly. I use CI3 in Debian 11 running xampp8.1
**Configure your upload path**
After upload this will send you upload data or the upload error
$config = array(
'upload_path' => "./assets/img/report/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
else
{
$error = array('error' => $this->upload->display_errors());
}
}

405 Method Not Allowed response: { "message": "The GET method is not supported for this route. Supported methods: POST."}

I created an API with tymon/jwt-auth, I test it on POSTMAN and it works very well, but when I want to consume it with Guzzle I encountered this error :
GuzzleHttp\Exception\ClientException Client error: POST http://localhost/project/public/api/stands/1/images2/ resulted in a
405 Method Not Allowed response: { "message": "The GET method is not
supported for this route. Supported methods: POST.", "exception":
"Symfony\ (truncated...)
Route for API :
Route::post('stands/{id}/images2', 'ImageController#store');
Controller ImageController.php for API :
public function store(Request $request, $id) {
$validator = Validator::make($request->all(),
[
'nom' => 'required|mimes:jpeg,png'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
if ($files = $request->file('nom'))
{
$path = public_path() . '/images/';
$files->move($path, $files->getClientOriginalName() );
$image = new Image();
$image->nom = $files->getClientOriginalName();
// $image->stand_id= $request->stand_id;
$stand = $this->user->stands()->find($id);
if ($stand->images()->save($image)){
return response()->json([
'success' => true,
"message" => "File successfully uploaded"
]);
$image->save();
}
else{
return response()->json([
'success' => false,
'message' => 'Sorry, image could not be added'
], 500);
}
}
}
Form :
<form method="POST" enctype="multipart/form-data" action="{{ route('postImage',request()->route('id')) }}">
{{ csrf_field() }}
{{ method_field("post")}}
<!--begin::Card-->
<div class="card card-custom gutter-b example example-compact">
<div class="card-header">
<div class="card-title">
<h3 class="card-label">
Upload
</h3>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="box-browse" >
<div class="custom-file">
<input type="file" name="nom" class="custom-file-input" id="inputGroupFile01">
</div>
<div class="content-upload">
<i class="fa fa-download" aria-hidden="true"></i>
</div>
<span class="form-text text-muted">Allowed file types: png, jpg,
jpeg.</span>
<!-- <div class="custom-file">
<label class="custom-file-label" for="customFile">Choose
file</label>
</div> -->
</div>
</div>
</div>
</div>
</div>
<!--end::Card-->
<input type="submit" name="submit" value="ok" />
</form>
Controller Admin\ImageController.php that consumes API for upload file :
public function store(Request $request, $id){
$file = $request->file('nom');
$file_path = $file->getPathname();
$file_mime = $file->getMimeType('image');
$file_uploaded_name = $file->getClientOriginalName();
$url = "http://localhost/project/public/api/stands/".$id."/images2/";
$client = new \GuzzleHttp\Client();
try {
$response = $client->post($url,
[
'multipart' => [
[
'name' => 'nom',
'filename' => $file_uploaded_name,
'Content-Type' => 'multipart/form_data',
'contents' => fopen($file_path, 'r'),]
],
'headers' =>
[
'Authorization' => 'Bearer '.Session::get('token'),
'Accept' => 'application/json',
'Content-Type' => 'multipart/form_data',
]
]);
} catch (Exception $e) {
}
the route :
Route::post('/stands/{id}/images2/', 'Admin\ImageController#store')->name('postImage');

foreach loop for two variables in laravel

below is my codes in controller and php file. How do I run the foreach for both $posts and $users? I have tried #foreach(array_merge($posts,$users) as $post) but doesn't work.
WelcomeController:
public function index()
{
$posts = Post::all();
$users = User::all();
return view('welcome', [
'posts' => $posts,
'users' => $users
]);
}
blade.php:
#foreach($posts as $post)
<div class="column">
<div class="content">
<img src="/storage/{{$post->image}}" style="width:100%" id="myImg">
<h4>By {{$user->name}}</h4>
<p>{{$post->caption}}</p>
<p class="description">{{$post->description}}</p>
</div>
</div>
#endforeach
I suggest you to use one to many (inverse) relationship visit
In post model add:
public function user()
{
return $this->belongsTo('App\Models\User');
}
And in blade.php:
{{ $post->user->name }}

Yii2 Dynamic Form

I'm using wbraganca's dynamicform samples codes for mine own project. My code with its corresponding errors are as follows.
Under the view folder
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Items;
use frontend\models\Employees;
use frontend\models\Departments;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model backend\models\Borrow */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
';
$this->registerJs($js);?>
<div class="borrow-form">
<?php $form = ActiveForm::begin(['id'=>'dynamic-form']); ?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($model,'dept_id')->dropDownList(
ArrayHelper::map(Departments::find()->all(),'id','dept_name'),
['prompt'=>'select departments'])
?>
</div>
<div class="col-xs-4">
<?=$form->field($model, 'return_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="padding-v-md">
<div class="line line-dashed"></div>
</div>
<!-- beginning of dynamic form -->
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be added (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'items_id',
'unit',
'request',
'allowed',
],
]); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Items
</h4>
</div>
<div class="panel-body">
<div class="container-items"><!-- widgetBody -->
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="item panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Items</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]id");
}
?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($modelAddress, "[{$i}]items_id")->dropDownList(
ArrayHelper::map(Items::find()->all(),'id','item_name'),
['prompt'=>'select items']) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]request")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]allowed")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit_price")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div><!-- .panel -->
<?php DynamicFormWidget::end(); ?>
<!-- end dynamic form-->
<div class="row">
<div class="col-xs-5">
<?= $form->field($model,'emp_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select employees'])
?>
<?= $form->field($model,'head_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select dept heads'])
?>
<?= $form->field($model,'man_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke managers'])
?>
<?= $form->field($model,'keeper_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke keepers'])
?>
</div>
<div class="col-xs-5">
<?=$form->field($model, 'emp_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'head_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'man_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'keeper_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The create action under the controller
public function actionCreate()
{
$model = new Borrow();
$modelsAddress = [new Borrow];
if ($model->load(Yii::$app->request->post())) {
$modelsAddress = Model::createMultiple(Borrow::classname());
Model::loadMultiple($modelsAddress, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAddress) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsAddress as $modelAddress) {
$modelAddress->id = $model->id;
if (! ($flag = $modelAddress->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('create', [
'model' => $model,
'modelsAddress' => (empty($modelsAddress)) ? [new Address] : $modelsAddress
]);
}
The Model Class under the Model Folder
<?php
namespace frontend\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $borrow) {
if (isset($borrow['id']) && !empty($borrow['id']) && isset($multipleModels[$borrow['id']])) {
$models[] = $multipleModels[$borrow['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
It gives the following error when I run my code:
PHP Fatal Error – yii\base\ErrorException Class 'frontend\controllers\Model' not found as shown below.
It looks like you have not namespaced frontend\models\Model in the controller.
Add there at the beginning:
use frontend\models\Model;

Symfony 3 form + Aurelia

So i've playing around with building a web app in Symfony 3, using a form type and rendering the form on the page. I am starting to Aurelia, and am trying to render a Symfony form on the page via an Aurelia custom element, and then post the form back to symfony. I've gotten to the point of validating the form upon submit, but it never validates. Can someone please look over the below code and see if i'm missing something somewhere?
Form type:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Service\PayeeService;
class PayeeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('category', ChoiceType::class, [
'choices' => [
'Uncategorized' => PayeeService::CATEGORY_UNCATEGORIZED,
'Installment Loan' => PayeeService::CATEGORY_INSTALLMENT_LOAN,
'Credit Card' => PayeeService::CATEGORY_CREDIT_CARD,
'Utility' => PayeeService::CATEGORY_UTILITY,
'Mortgage' => PayeeService::CATEGORY_MORTGAGE,
'Entertainment' => PayeeService::CATEGORY_ENTERTAINMENT
],
'choices_as_values' => true
])
->add('amount', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('frequency', ChoiceType::class, [
'choices' => [
'Recurring' => PayeeService::FREQUENCY_RECURRING,
'One-time' => PayeeService::FREQUENCY_ONETIME
],
'choices_as_values' => true
])
->add('method', ChoiceType::class, [
'choices' => [
'ACH' => PayeeService::PAY_METHOD_ACH,
'Check' => PayeeService::PAY_METHOD_CHECK
],
'choices_as_values' => true
])
->add('dateLastPaid', DateType::class)
->add('dueDate', DateType::class)
->add('gracePeriod', IntegerType::class)
->add('balance', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('active', CheckboxType::class, ['label' => 'Active', 'data' => true])
->add('save', SubmitType::class, ['label' => 'Save Payee'])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Payee'
));
}
}
Controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
class FormController extends Controller
{
/**
* #Route("/_form/entity/{entity}", name="new_entity_form")
* #Method("GET")
*/
public function getFormForNewEntity(Request $request)
{
$rawName = $request->get('entity');
$content = $request->getContent();
$data = json_decode($content, true);
$formName = strtolower($rawName) . "_form";
$submitFunction = $data['submitFunction'];
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
return $this->render('form/form.html.twig', [
'name' => $formName,
'form' => $form->createView(),
'submitFunction' => $submitFunction]);
}
/**
* #Route("/_form/entity/{entity}", name="new_entity_create")
* #Method("POST")
*/
public function saveFormForNewEntity(Request $request)
{
$em = $this->getDoctrine()->getManager();
$rawName = $request->get('entity');
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return new JsonResponse(['result' => true]);
} elseif ($form->isEmpty()) {
return new JsonResponse(['result' => false, 'errors' => 'form empty']);
} else {
return new JsonResponse(['result' => false, 'errors' => iterator_to_array($form->getErrors(true))]);
}
}
}
Form twig:
{{ form_start(form, {'attr': {'id':name, 'role':'form', 'submit.delegate':submitFunction}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Aurelia component js:
import {InlineViewStrategy} from 'aurelia-framework';
import {customElement, bindable, inject} from 'aurelia-framework';
import $ from 'jquery';
import {HttpClient} from 'aurelia-http-client';
import 'fetch';
#customElement('symfony-form')
#inject(Element)
export class SymfonyForm {
#bindable entity;
constructor(element) {
this.content = '';
this.http = new HttpClient();
this.http.configure(config => {
config
.withBaseUrl('http://localhost:8000/');
});
this.element = element;
}
bind(binding, override) {
return this.http.get('_form/entity/' + this.entity, {'submitFunction': 'submit()'})
//.then(response => response.html())
.then(response => {
this.content = response.response;
});
}
submit() {
// application/x-www-form-urlencoded
this.http.createRequest('_form/entity/' + this.entity)
.withHeader('Content-Type', 'application/x-www-form-urlencoded')
.asPost()
.withContent($(this.element).find('form').serialize())
.send()
.then(response => {
alert(response.response);
});
//alert('submitted ' + this.entity);
// return this.http.post('_form/entity/' + this.entity, $(this.element).find('form').serialize())
// .then(response => {
// alert(response.response);
// });
}
}
aurelia component view:
<template>
<form role="form" submit.delegate="submit()">
<div innerHTML.bind="content"></div>
</form>
</template>
aurelia page:
<template>
<require from="form"></require>
<section class="au-animate">
<h2>${heading}</h2>
<form role="form" submit.delegate="submit()">
<div class="form-group">
<label for="fn">First Name</label>
<input type="text" value.bind="firstName" class="form-control" id="fn" placeholder="first name">
</div>
<div class="form-group">
<label for="ln">Last Name</label>
<input type="text" value.bind="lastName" class="form-control" id="ln" placeholder="last name">
</div>
<div class="form-group">
<label>Full Name</label>
<p class="help-block">${fullName | upper}</p>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<symfony-form entity="Payee"></symfony-form>
</section>
</template>
I'm not an expert on SPAs, or JS frameworks, but from what I can see the problem is the lack of a CSFR field with the correct token and also that I don't believe your inputs are named correctly for symphony to read them correctly (I may have missed where this is handled so apologies if so). You need to have the input name formatted as below:
<input type="text" name="formname[formfield]" />
So for example I believe you need your name field to be:
<input type="text" name="payeetype[name]" />