I'm having problem that I would like to send Email with multiple images in Laravel9.
I wrote below code.
My goal is send Email with multiple images and
sametime each image file name stores into mysql's 'fileattach' column as photo1, photo2, photo3(one line)
Could someone correct my code please?
blade file
<div class="col-sm-6">
<input type="file" name="files[]" accept="file_extension|image/*|media_type" multiple>
</div>
Controller
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),custom name
'mime' => $file->getMimeType())
);
}
}
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
});
You are almost there, need to put the attachment code into callback method to mail.
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
//Get the $files array here
$files = [];
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request, $files)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),//custom name
'mime' => $file->getMimeType())
);
}
}
});
}
Related
i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong
There are an error showing when i add #if ({{Auth::user()->utype}} == "ADM") Line of code in product.blade.php.
</head>
#if ({{Auth::user()->utype}} == "ADM")
<body>
</body>
#endif
This is my controller named ProductController.
public function index()
{
$products = Product::all();
return view('product', compact('products'));
}
public function create()
{
return view('product');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'brand' => 'required',
'detail' => 'required',
'size' => 'required',
'type' => 'required',
'price' => 'required',
'image' => 'required',
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'image' => $new_name,
'name' => $request->input('name'),
'size' => $request->input('size'),
'type' => $request->input('type'),
'price' => $request->input('price'),
'detail' => $request->input('detail'),
'brand' => $request->input('brand'),
);
Product::create($form_data);
return redirect()->route('product.index')->withSuccess('Done');
}
enter image description here
Please help me to solve the mistake.
You are already using blade directive, so no need to put {{}}, inside #if or any other directive try this
#if (Auth::user()->utype == "ADM")
<body>
</body>
#endif
I'm using the Spatie MediaLibrary library in a Laravel application. I want to upload 0 or more photos to my app via a REST API.
I can get it to work when the photo attribute contains 1 file
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable|file'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
// stores the photo
if ($request->hasFile('photo')) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
return new ListingResource($listing);
}
The postman request looks as follows:
I know want to change the code so it can handle multiple photos in the request. I'm using the following code in the controller above to do so:
if ($request->hasFile('photo')) {
foreach ($request->input('photo', []) as $photo) {
$listing->addMediaFromRequest('photo')->toMediaCollection('photos');
}
}
and I have changed the attribute to photos[] instead of photo.
The code never goes into the foreach loop even.
Anyone has a hint on how to solve this?
Apparently the Spatie Medialibrary has a function called addMultipleMediaFromRequest. The full code is now
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required',
'description' => 'required',
'price' => 'required|integer',
'photo' => 'nullable'
]);
$listing = Listing::Create([
'user_id' => auth('api')->user()->id,
'name' => $request->name,
'slug' => $request->slug,
'description' => $request->description,
'price' => $request->price,
]);
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
return new ListingResource($listing);
}
In Postman, I'm calling it as follows:
documentation reference
I managed to upload multiple files like this:
if($request->file('photos')) {
foreach ($request->file('photos') as $photo) {
$post->addMedia($photo)->toMediaCollection('post');
}
}
Check this out:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240
This code is working for me.
View
<input type="file" name="photo[]" multiple />
ListingController
public function store(Request $request)
{
if ($request->hasFile('photo')) {
$fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
->each(function ($fileAdder) {
$fileAdder->toMediaCollection('photos');
});
}
}
i am trying to first set in controller setOption(value, valuename) in controller and store in database and use it as getOption in views
but not working .
Here is my controller =>
public function edit(Request $request)
{
mpc_m_c($request->server('SERVER_NAME'));
$options = Config::all()->pluck('value','name');
$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
return view('admin.system-settings', compact('options', 'tzlist'));
}
public function update(Request $request)
{
$this->validate($request, [
'app_name' => 'required',
'currency_symbol' => 'required',
'currency_code' => 'required',
'date_format' => 'required',
'home_page_description' => 'required',
'recaptcha_private_key' => 'required',
'minimum_deposit_amount' => 'required',
'home_page_meta' => 'required',
'notify_email' => 'required'
]);
if ($request->hasFile('logo')) {
$file = $request->file('logo');
$fileArray = array('logo' => $file);
$rules = array(
'logo' => 'mimes:png|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['logo' => $errors['logo']]);
} else {
$logo = Storage::putFile('images', $request->file('logo'));
setOption('logo', $logo);
}
}
if ($request->hasFile('banner')) {
$file = $request->file('banner');
$fileArray = array('banner' => $file);
$rules = array(
'banner' => 'mimes:png,jpg,jpeg|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['banner' => $errors['banner']]);
} else {
$banner = Storage::putFile('images', $request->file('banner'));
setOption('banner', $banner);
}
}
setOption('app_name', $request->input('app_name'));
setOption('currency_symbol', $request->input('currency_symbol'));
setOption('currency_code', $request->input('currency_code'));
setOption('date_format', $request->input('date_format'));
setOption('home_page_description', $request->input('home_page_description'));
setOption('recaptcha_public_key', $request->input('recaptcha_public_key'));
setOption('recaptcha_private_key', $request->input('recaptcha_private_key'));
setOption('minimum_deposit_amount', $request->input('minimum_deposit_amount'));
setOption('home_page_meta', $request->input('home_page_meta'));
setOption('module_support_enabled', $request->input('module_support_enabled'));
setOption('module_api_enabled', $request->input('module_api_enabled'));
setOption('module_subscription_enabled', $request->input('module_subscription_enabled'));
setOption('theme_color', $request->input('theme_color'));
setOption('background_color', $request->input('background_color'));
setOption('language', $request->input('language'));
setOption('display_price_per', $request->input('display_price_per'));
setOption('admin_layout', $request->input('admin_layout'));
setOption('user_layout', $request->input('user_layout'));
setOption('panel_theme', $request->input('panel_theme'));
setOption('anonymizer', $request->input('anonymizer'));
setOption('front_page', $request->input('front_page'));
setOption('show_service_list_without_login', $request->input('show_service_list_without_login'));
setOption('notify_email', $request->input('notify_email'));
setOption('currency_separator', $request->input('currency_separator'));
setOption('timezone', $request->input('timezone'));
Session::flash('alert', __('messages.updated_logout_needed'));
Session::flash('alertClass', 'success');
return redirect('/admin/system/settings');
}
route =>
Route::get('/system/settings', 'ConfigController#edit');
Route::put('/system/settings', 'ConfigController#update');
error =>
"Call to undefined function App\Http\Controllers\Admin\setOption()"
and view =>
<div class="form-group{{ $errors->has('home_page_meta') ? ' has-error' : '' }}">
<label for="home_page_meta" class="control-label">meta tags</label>
<textarea
style="height: 150px;"
class="form-control"
data-validation="required"
rows="5"
id="home_page_meta"
name="home_page_meta"> <?php echo e($options['home_page_meta']) ?></textarea>
</div>
use =>
getOption('valuename')
And by this things he is using the function getOption(''valuename) anywhere in the entire application ... i really dont want use it but just curious How he is using this things even there's no laravel build in funtion for this name?
*Note : Please don't judge me , I just want to know ..thnaks
anybody got idea how do i use it ?
The validate() function from my sales controller seems not working, I am comparing it to my other controller, it looks like it should work but it is not. it looks like the validate() is being bypassed. here's my controller
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class SalesController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required',
'status_id' => 'required',
'currency_id' => 'required',
'company_id' => 'required',
'invoice_no' => 'nullable',
'notes' => 'nullable',
'admin_notes' => 'nullable',
'due_date' => 'nullable',
'publish' => 'nullable',
'product_id' => 'required|min:1',
'product_code' => 'required|min:1',
'product_name' => 'required|min:1',
'quantity' => 'required'
]);
$sales = $request->only(
'user_id',
'status_id',
'currency_id',
'currency_rate',
'due_date',
'company_id',
'invoice_no',
'notes',
'admin_notes',
'delivery_date',
'publish'
);
$sales['grandtotal'] = (float) str_replace(',', '', $request->grandtotal);
$sales['grandtotalcost'] = (float) str_replace(',', '', $request->grandtotalcost);
$sales = Sales::create($sales);
$input = $request->all();
for($i=0; $i<= count($input['quantity']); $i++) {
if(empty($input['quantity'][$i]) || !is_numeric($input['quantity'][$i])) continue;
$items = [
'sales_id' => $sales->id,
'product_id' => $input['product_id'][$i],
'product_code' => $input['product_code'][$i],
'product_name' => $input['product_name'][$i],
'price' => $input['price'][$i],
'cost' => $input['cost'][$i],
'quantity' => intval($input['quantity'][$i]),
'total_price' => (float) str_replace(',', '', $input['total_price'][$i]),
'total_cost' => (float) str_replace(',', '', $input['total_cost'][$i]),
];
Salesitems::create($items);
}
// $ponumbers = Ponumbers::create($request->only('purchase_no'));
$invnum = $request->all();
$invnumbers = new Invnumbers;
$invnumbers->sales_num = $invnum['invoice_no'];
$invnumbers->save();
if ($request){
Session::flash('message','Invoice was successfully added');
Session::flash('m-class','alert-success');
} else {
Session::flash('message','Data is not saved');
Session::flash('m-class','alert-danger');
return redirect()->route('sales.index');
}
return redirect()->route('sales.index');
}
}
My Blade
<input class="form-control autocomplete_txt product_name" type='text' data-type="product_name" id='product_name_1' name='product_name[]' for="1" readonly/>
#if ($errors->has('product_name')) <p class="help-block">{{ $errors->first('product_name') }}</p> #endif
if I submit my form with product name, instead of throwing error from validate,
By seeing your code, to me it seems your product_id should be an array. So the validation should be:
'product_id' => 'array|required|min:1',
'product_id.*' => 'required',
instead of
'product_id' => 'required|min:1',
Try to use $request->validate([... instead of $this->validate($request, [.... I'm not sure is there validate in your controller...