I can't understand what the problem may be:
I state that the code without the part of the attachment works
function submit(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'file' => 'mimes:pdf,doc,docx'
]);
$data = array(
'name_data' => $request->name,
'cognome_data' => $request->cognome,
'luogo_data' => $request->luogo,
'date_data' => $request->date,
'telefono_data' => $request->telefono,
'email_data' => $request->email,
'citta_data' => $request->citta,
'provincia_data' => $request->provincia,
'studio_data' => $request->studio,
'lingua_data' => $request->lingua,
'livello_data' => $request->livello,
'lingua2_data' => $request->lingua2,
'livello2_data' => $request->livello2,
'file_data' => $request->file,
'agree_data' => $request->agree
);
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('pipo#gmail.com', 'piooi')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if ( isset($data['file_data']))
{
$message->attach($data['file_data']->getRealPath(), array(
'as' => $data['file_data']->getClientOriginalName(),
'mime' => $data['file_data']->getMimeType()));
}
});
Session::flash('success', 'Mail spedita con sucesso');
}
}
I put the piece of the form in question:
<form class="text-left form-email"action="#" enctype="multipart/form-data" method="POST">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Curriculum Vitae:</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="file" name="file"
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Seleziona il file</label>
</div>
</div>
the error that gives the summit is the following:
local.ERROR: Call to a member function getRealPath() on null {"exception":"[object] (Error(code: 0):
Change your mail part to this and see if it works
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('pipo#gmail.com', 'piooi')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if($request->hasFile('file')){
$message->attach($request->file->getRealPath(), array(
'as' => $request->file->getClientOriginalName(),
'mime' => $request->file->getMimeType())
);
}
});
Related
i'm trying to upload image and video at the same time but couldn't
i've tried this but it seems to not work, the image file will upload successfully but the video won't
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
$file = new Film();
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['file' => $file_name]);
$film->update(['path' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
if ($request->file('video')){
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$file->name = time().'_'.$request->file->getClientOriginalName();
$file->file = '/storage/' . $file_path;
$film->update(['video' => $file_name]);
$film->update(['videoPath' => $file_path]);
return response()->json(['success'=>'File uploaded successfully.']);
}
It's because you are returning a response after you process the image file so the condition for the video can't be reached. If you want to process both just return after all the operations are done.
$request->validate([
'title'=> 'required',
'description' => 'required',
'file' => 'required|mimes:jpg,jpeg,png|max:2048',
'video' => 'required|mimes:mp4'
]);
$film= Film::create([
'title' => $request->title,
'slug' => Str::slug($request->title),
'description' => $request->description,
'user_id' => auth()->id()
]);
if($request->file('file')) {
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file')->storeAs('uploads', $file_name, 'public');
$film->update([
'file' => $file_name,
'path' => $file_path
]);
}
if ($request->file('video')){
$file_name = time().'_'.$request->video->getClientOriginalName();
$file_path = $request->file('video')->storeAs('uploads', $file_name, 'public');
$film->update([
'video' => $file_name,
'videoPath' => $file_path
]);
}
return response()->json(['success'=>'Files uploaded successfully.']);
You can also add additional checks if the files inside each condition is processed successfully.
The $file variable is unnecessary and it's not even saved so that can be removed as well.
As for the reason it's uploading twice, you are calling ->file again inside the video condition which should be ->video.
And as an aside, you can update multiple fields at once by passing multiple array items instead of calling update for each property which can save you db requests.
jech chua, thanks it worked but it uploads the image twice.
maybe there a problem in my blade
<form action="/film" class="form" method="POST" enctype="multipart/form-data">
#csrf
<div class="f">
<div class="sect1">
<input type="text" class="input" name="title" placeholder="Title..">
<textarea name="description" class="textarea" placeholder="Description.."></textarea>
<h2>Upload image</h2><input type="file" name="file" class="file">
</div>
<div class="dropz" id="image-upload">
<h2>Upload video</h2>
<input type="file" name="video">
</div>
</div>
<button type="submit" class="buttn">Create film</button>
</form>
I’m working on a CRUD system for inventory management, in which images for each product should be included. Every time that I try to save the path of the image in the DB this error appears:
Undefined variable: image
My controller looks like this:
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required',
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
}
$product['Product_Image'] = $image;
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}
and my input looks like this:
<form method="post" action="{{url('loginv')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="row">
<div class="col-md-12"></div>
<div class="form-group col-md-12">
<label for="Product_Image">Product Image:</label>
<input type="file" class="form-control" name="Product_Image">
</div>
</div>
and dd($request->all()); delivers this
array:8 [▼ "_token" => "P7m8GP4A35G1ETUosduBSWtMpJuPaNILn2WI6Al3"
"Product_Image" => "6.jpg" "Product_Name" => "asd" "Amount" =>
"123" "MinAmount" => "1" "Status" => "Ok" "Supplier" => "asd"
"WebLink" => "asd" ]
Change your code to
public function store(Request $request)
{
if (Auth::user('logistics')) {
$product = $this->validate(request(), [
'Product_Name' => 'required',
'Amount' => 'required|numeric',
'MinAmount' => 'required|numeric',
'Status' => 'required',
'Supplier' => 'required',
'WebLink' => 'required'
]);
if ($request->hasFile('Product_Image')) {
$image = Storage::putFile('public/pictures/LogInv/', $request->Product_Image);
$product['Product_Image'] = $image;
}
$product['Employee_id'] = Auth::user()->id;
LogisticsInv::create($product);
return back()->with('success', 'Product has been added');
} else {
return view('/restricted_area');
}
}
I'm a novice when it comes to PHP and Laravel and am embarrassed that I haven't figured this out yet. I'm trying to provide an option for my user to import their database into the application. However, I need to attach a user id to each row so it can be saved with that user. I've tried multiple attempts to grab that user id and pass it into the foreach loop so it can be saved. Any guidance I can receive, I'd be most grateful. I am using Maatwebsite/Laravel-Excel facade.
Here is my Controller:
class ImportController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
$insert[] = [
'user_id' => $value->user_id,
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
}
Here is my route:
Route::post('importExcel', 'ImportController#importExcel');
Here is my view:
<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#importExcel">Import</button>
<div class="modal fade" id="importExcel" tabindex="-1" aria-labelledby="importExcelLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Import Your Database</h4>
</div>
<div class="modal-body">
<p>Click browse to import your database. Only Microsoft Excel extensions are acceptable. Please label your columns as follows:</p>
<ul>
<li>user_id (leave this column empty)</li>
<li>first_name</li>
<li>last_name</li>
<li>title</li>
<li>level</li>
<li>company</li>
<li>address_1</li>
<li>address_2</li>
<li>city</li>
<li>state</li>
<li>zip_code</li>
<li>office_tel</li>
<li>mobile_tel</li>
<li>member_since</li>
</ul>
<form action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
<input type="hidden" name="_token" value="{{csrf_token()}}">
<button type="submit" class="btn btn-primary">Import File</button>
</form>
</div><!-- /.modal-body-->
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div><!-- /.modal-footer-->
</div><!-- /.modal-content-->
</div><!-- /.modal-dialog-->
</div><!-- /.modal-->
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable = [
'user_id',
'first_name',
'last_name',
'title',
'level',
'company',
'email',
'address_1',
'address_2',
'city',
'state',
'zip_code',
'office_tel',
'mobile_tel',
'member_since' ];
}
First of all: Where do you set $insert? You have to set this variable with the data you like to import. Despite of that you can try the following:
If I understand you right, the database-field user_id should contain the ID of the logged in user - if so, try in your controller the following in importExcel (see comment):
public function importExcel(Request $request)
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$user = Auth::user();
$data['user_id'] = $user->id;
[
'user_id' => $user->id, // Access here the userId of the logged in user
'first_name' => $value->first_name,
'last_name' => $value->last_name,
'title' => $value->title,
'level' => $value->level,
'company' => $value->company,
'email' => $value->email,
'address_1' => $value->address_1,
'address_2' => $value->address_2,
'city' => $value->city,
'state' => $value->state,
'zip_code' => $value->zip_code,
'office_tel' => $value->office_tel,
'mobile_tel' => $value->mobile_tel,
'member_since'=> $value->member_since
];
}
if(!empty($insert)){
DB::table('members')->insert($insert);
Session::flash('flash_message', 'Database successfully imported!');
}
}
}
return back();
}
Hope that helps :)
I'm building my first app with Laravel 5.2 & Laravel Spark. The front end is built using Vue.js I believe and despite adding the following to register-common-form.blade.php:
<!-- Username -->
<div class="form-group" :class="{'has-error': registerForm.errors.has('username')}">
<label class="col-md-4 control-label">Username</label>
<div class="col-md-6">
<input type="name" class="form-control" name="username" v-model="registerForm.username" autofocus>
<span class="help-block" v-show="registerForm.errors.has('username')">
#{{ registerForm.errors.get('username') }}
</span>
</div>
</div>
I can't actually see a way to fully register that extra field so that it is picked up for error handling. I've got it so that the UserRepository handles the field and inserts it, but just can't get the front end errors to show properly.
Is anyone able to help with this at all?
Okay I finally stumbled across it :D
In Laravel\Spark\Interactions\Auth\CreateUser.php there is a $rules method like so:
public function rules($request)
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
All I have done is add my username field, and it works brilliantly!
public function rules($request)
{
return [
'name' => 'required|max:255',
'username' => 'required|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'vat_id' => 'max:50|vat_id',
'terms' => 'required|accepted',
];
}
Above answer is just for validation rules you also need to navigate to spark\src\Repositories\UserRepository.php and add 'username' => $data['username'], to the create() method like this:
public function create(array $data)
{
$user = Spark::user();
$user->forceFill([
'name' => $data['name'],
'username' => $data['username'], // ADDED THIS
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => str_random(30),
'last_read_announcements_at' => Carbon::now(),
'trial_ends_at' => Carbon::now()->addDays(Spark::trialDays()),
])->save();
return $user;
}
I'm trying to display validation errors with CakePHP (Newbie) but I'm stuck. I get this error "Delimiter must not be alphanumeric or backslash". Don't know if the logic is respected, I'm starting from scratch.
Nothing is displayed. Here's my code:
User model
class User extends AppModel {
public $validate = array(
'nom' => array(
'message' => 'Saisie obligatoire',
'required' => true
),
'prenom' => array(
'message' => 'Saisie obligatoire',
'required' => true
),
'date_naissance' => array(
'rule' => array('date','dmy'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
'allowEmpty' => true
),
'email' => array(
'rule' => 'email',
'message' => 'Veuillez introduire une adresse mail valide',
'required' => true
),
'password' => array(
'rule' => 'password',
'message' => 'Un mot de passe est requis'
)
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
add function into UsersController
public function add() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Auth->login($this->User);
return $this->redirect('/index');
}
}
} else {
return $this->User->validationErrors;
}
}
add.ctp
<?= $this->element('navbar');?>
<div class="formcontainer">
<div class="page-header">
<h1>Rejoignez-nous</h1>
</div>
<form action="/users/add" id="UserAddForm" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST"/>
</div>
<div class="form-group input text">
<label for="UserNom">Nom:</label>
<input name="data[User][nom]" maxlength="20" type="text" id="UserNom" class="form-control" placeholder="requis">
</div>
<div class="form-group input text">
<label for="UserPrenom">Prénom:</label>
<input name="data[User][prenom]" maxlength="20" type="text" id="UserPrenom" class="form-control" placeholder="requis">
</div>
<div class="form-group input text">
<label for="UserDateNaissance">Date de naissance:</label>
<input name="data[User][date_naissance]" maxlength="20" type="text" id="UserDateNaissance" class="form-control">
</div>
<div class="form-group input email">
<label for="UserEmail">Email:</label>
<input name="data[User][email]" maxlength="100" type="email" id="UserEmail" class="form-control" placeholder="requis"/>
</div>
<div class="form-group input password">
<label for="UserPassword">Mot de passe:</label>
<input type="password" name="data[User][password]" class="form-control" id="UserPassword" placeholder="requis">
</div>
<button type="submit" class="btn btn-default bSub">M'inscrire</button>
</form>
</div>
Your validation should be like this(You must add rule for field and there is no inbuilt passowrd rule in cakephp).
public $validate = array(
'nom' => array(
'rule' => 'notEmpty', //add rule here
'message' => 'Saisie obligatoire',
'required' => true
),
'prenom' => array(
'rule' => 'notEmpty', //add rule here
'message' => 'Saisie obligatoire',
'required' => true
),
'date_naissance' => array(
'rule' => array('date', 'dmy'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
'allowEmpty' => true
),
'email' => array(
'rule' => 'email',
'message' => 'Veuillez introduire une adresse mail valide',
'required' => true
),
'password' => array(
'rule' => 'notEmpty', //there is no inbuilt validation rule with name *password*
'message' => 'Un mot de passe est requis'
)
);
If you want to show error message then you should use Form Helper for create form inputs like this
echo $this->Form->input("User.nom", array("class"=>"form-control", "placeholder"=>"requis", 'label'=>false));
Or you can display message by using isFieldError method of Form helper
if ($this->Form->isFieldError('nom')) {
echo $this->Form->error('nom');
}
// Model
class User extends AppModel {
public $validate = array(
'password' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Un mot de passe est requis'
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Veuillez introduire une adresse mail valide',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'date_naissance' => array(
'date' => array(
'rule' => array('date'),
'message' => 'Veuillez respecter le format de la date (jour/mois/année)',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'prenom' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Saisie obligatoire',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'nom' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'Saisie obligatoire',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
// Controller
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
// add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('password');
echo $this->Form->input('email');
echo $this->Form->input('date_naissance');
echo $this->Form->input('prenom');
echo $this->Form->input('nom');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users'), array('action' => 'index')); ?></li>
</ul>
</div>