Laravel 5.8 send email with file attachment - laravel

I'm trying to send an email with attachment in laravel 5.8 using markdown. Its working just fine email alone without attachment. How can I get to send with attachment?
Form's view:
<form action="{{url('deputyheadteacher-email')}}" method="post" enctype="multipart/form- data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group">
<input type="text" class="form-control" name="subject" placeholder="Subject" required/>
</div>
<div class="form-group">
<textarea class="textarea" name="message" placeholder="Message" required
style="width: 100%; height: 125px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
<div class="form-group">
<input type="file" id="att" name="att"/>
</div>
</div>
<div class="box-footer clearfix">
<button class="pull-right btn btn-default" id="sendEmail">Send <i class="fa fa-arrow-circle-right"></i></button>
</div>
</form>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;
use App\User;
use Auth;
use Input;
use App\Mail\DeputyHeadTeacherMailAll;
use Illuminate\Support\Facades\Mail;
class DeputyHeadTeacherEmailController extends Controller
{
public function mail(Request $request)
{
$users = User::all();
$user = Auth::user();
$fname = $user->fname;
$sname = $user->sname;
$role = $user->role->name;
$file = $request->file('att');
$file1 = $request->att;
f($request->hasFile('att'))
{
$image = $request->file('att');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/files/');
$image->move($destinationPath, $name);
}
else
{
$name = "";
}
//exit();
//echo $file1." - ".$file; exit();
$mime = 'image/png';
$display = 'campaign';
$data = array(
'subject' => $request->subject,
'bodyMessage' => $request->message,
'attachment' => $file,
'attachment1' => $file1,
'name' => $name,
'mime' => $mime,
'display' => $display,
'fname' => $fname,
'sname' => $sname,
'role' => $role,
);
foreach($users as $user)
{
$email = $user->email;
Mail::to($email)->send(new DeputyHeadTeacherMailAll($data));
}
/*
Mail::send('emails/deputyheadteachersendalll',$data,function($message)
{
$message->to('mikejosephm52#gmail.com')->subject('Test123');
$message->from('info#brightrock.co.ke');
});*/
Session::flash('success','Your email was sent!!!');
return back();
}
}
Mailable:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
class DeputyHeadTeacherMailAll extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
//
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
//return $this->view('emails.deputyheadteachersendalll')->attach('files/'.$this->data['name']);
//return $this->markdown('emails.deputyheadteachersendall')->subject($this->data['subject']);
return $this->markdown('emails.deputyheadteachersendall')->attach('files/1587758910.jpg')->subject($this->data['subject']);
}
}
For the above build fx, the second commented line works though sends without attachment.
The last line is an attempt to send with a pic from public/files folder.
Last but not least, the config/filesystems:
'disks' =>
[
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
],
],
Your help is greatly appreciated

User atttachFromStorage method instead:
public function build()
{
return $this->view('emails.deputyheadteachersendalll')-> attachFromStorage('files/'.$this->data['name']);
}
Read more here: https://laravel.com/docs/5.8/mail#attachments
If you want to use different disk than default then use attachFromStorageDisk instead. Example:
return $this->view('emails.deputyheadteachersendalll')-> attachFromStorageDisk('files/'.$this->data['name'], 's3');

Related

trying to insert an array but Cannot access offset of type string on string laravel 8

i want to insert an array but it tells me Cannot access offset of type string on string
and i made foreach and when i do $return->request
it looks like
{
_token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
_method: "POST",
name: "Wanda Rojas",
phone: [
"+1 (841) 393-5088",
"+1 (769) 441-1936"
],
address: "Et est cum delectus"
}
and here is my model for clients
and i make phone field as array in protected $casts
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $fillable = [
'name',
'address',
];
protected $casts = [
'phone' => 'array'
];
}
here is my form
<form action="{{route('clients.store')}}" method="POST">
#csrf
#method('POST')
<input type="text" placeholder="add name" name="name"><br>
#for ($i = 0; $i < 2; $i++) <div class="form-group">
<label>#lang('site.phone')</label>
<input type="text" name="phone[]" class="form-control">
</div>
#endfor
<input type="text" placeholder="add address" name="address"><br>
<button type="submit" class="btn btn-primary">add</button>
</form>
and here is my controller at store method
public function store(Request $request)
{
//return $request;
$this->validate($request,[
'name' => 'required',
'phone' => 'required|array|min:1',
'phone.*' => 'required',
'address' => 'required'
]);
$phone = $request->phone;
foreach ($phone as $p){
$add = new Client();
$add->name = $request->name;
$add->phone = $p['phone'];
$add->address = $request->address;
$add->save();
};
return redirect()->route('clients.index');
}
Your code when you store client should looks like this
public function store(Request $request)
{
//return $request;
$this->validate($request,[
'name' => 'required',
'phone' => 'required|array|min:1',
'phone.*' => 'required',
'address' => 'required'
]);
$phone = $request->phone;
$add = new Client();
$add->name = $request->name;
$add->phone = $phone; // $phone it's already an array, so you should only set it to property
$add->address = $request->address;
$add->save();
return redirect()->route('clients.index');
}
and in clients.index.blade.php to access phone
#foreach($client->phone as $phone)
...
{{ $phone }}
...
#endforeach
You are iterating through the array of phone numbers so $p is the phone number. $add->phone = $p should resolve your issue.

Error App\Http\Requests\AddUserRequest::fails does not exist

I get this error when I want to insert data into the table and return a message.
Here is my code.
When I entered the form and submitted, an error occurred: Method App\Http\Requests\AddUserRequest::fails does not exist.
Code In Router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code In UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
{
return redirect('admin.add-user')
-> withInput()
-> withErrors($request);
}else
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
}
}
Code In view:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
#csrf
<div class="form-group">
#if (session('success'))
<div class="alert alert-success">
<p>{{ session('success') }}</p>
</div>
#endif
#if ($errors->any())
<div class="alert alert-danger">
<b>Lỗi!! Bạn vui vòng kiểm tra lại:</b>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
In AddUserRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class AddUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
];
}
}
Thank you for your help!
you don't need to put that check, because data is already validated through your request
public function getAdd(AddUserRequest $request)
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
AddUserRequest is a FormRequest it doesn't have fails method. For FormRequest you don't need to check fails, it automatically validate your request data using rules provided in that class and throw validation error, for details check here.
For FormRequest validation you use it like this
public function getAdd(AddUserRequest $request)
{
//all code here executed after validation
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
If you need to check validation in you controller then use manual validation like this.
public function getAdd(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'same:pass1',
]);
if($validator->fails())
{
return redirect('admin.add-user')
-> withInput()
-> withErrors($request);
}else
{
User::create([
'name' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->pass1),
'level' => 0,
]);
return redirect('admin.add-user')->with('success',"Done!!");
}
}

Payment preference, Mercadopago's SDK & Laravel 5.5

I'm having a problem while integrating MercadoPago's SDK and Laravel 5.5
Error message:
MercadoPagoException (400)
Wrong number of parameters
Screen:
error screen
Payment Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Cart;
use Exception;
use MP;
class PaymentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function process(Request $request)
{
$mp = new MP (env('MP_CLIENT_ID'), env('MP_CLIENT_SECRET'));
$user = auth()->user();
$prefix = 'VSHOPREF-';
$external_reference = $prefix . $request->ctoken;
$token = $request->ctoken;
$preferenceData = [
'external_reference' => $external_reference,
'payer' => [
'name' => $user->name,
'email' => $user->email
],
'back_urls' => [
'success' => env('APP_URL').'/gracias',
'pending' => env('APP_URL').'/gracias',
'failure' => env('APP_URL').'/error'
],
'notification_url' => env('MP_NOTIFICATION_URL'),
'auto_return' => 'all'
];
$entries = Cart::where('session_id', '=', $token)->get();
foreach ($entries as $e):
$preferenceData['items'][] = [
'title' => $e->product_name,
'category_id' => 'zapato',
'quantity' => $e->qty,
'currency_id' => 'VEF',
'unit_price' => $e->price,
];
endforeach;
//dd($preferenceData);
$preference = $mp->create_preference($preferenceData);
dd($preference);
//return init point to be redirected
//return $preference['response']['init_point'];
}
}
Form I'm using to send the payment information
<form class="form-horizontal" action="{!! route('payment.process') !!}" method="post">
{{ csrf_field() }}
<input type="hidden" name="ctoken" id="ctoken" value="{!! $cart_token !!}">
<input type="submit" name="pagar" value="Pagar" class="btn btn-success btn-block btn-sm">
</form>
Btw, I'm sorry for my bad english. I hope you can help me with this issue.
EDIT 1
Thanks to Alexey Mezenin
Well, i wrote "MP_CIENT_SECRET" instead of "MP_CLIENT_SECRET" on my .env file.
NEW ERROR
MercadoPagoException (400)
currency_id invalid

Laravel manually login always not match, in laravel 5.2

i keep having "not match" authentication using manually login with my laravel
here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;
use Input;
use Validator;
use Auth;
class CobaLogin extends Controller
{
public function index(){
return view('adminlogin');
}
public function username(){
return 'username';
}
public function doLogin(Request $request){
$username = $request ->input('username');
$password = $request -> input('password');
if(Auth::attempt(['username' => $username, 'password' => $password])){
echo "yes match";
}else{
echo "not match";
}
}
}
and here is my model from admin table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable{
protected $table = "admin";
}
here is my route
Route::get('loginadmin', 'CobaLogin#index');
Route::post('dologin', 'CobaLogin#doLogin');
here is my login blade file
<div class="wrapper">
<form class="form-signin" action="{{ url('dologin')}}" method="POST">
{{ csrf_field() }}
<br/><h2 class="form-signin-heading text-center">ADMIN LOGIN</h2>
<input type="text" class="form-control" name="username" placeholder="Email Address" required="" autofocus="" />
<input type="password" class="form-control" name="password" placeholder="Password" required=""/>
<label class="checkbox">
<input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
here is my auth.php file
'providers' => [
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
here is my register function
public function store(Request $request){
$data=Input::except(array('_token'));
// var_dump($data);
$rule=array(
'username' => 'required|unique:admin',
'password' => 'required|min:6',
'cpassword' => 'required|same:password',
'email' => 'required|email',
);
$message=array(
'username' => 'This username already taken',
'cpassword.min'=>'the password must at least 6 characters',
'cpassword.same'=>'the password and confirm password must same',
);
$validator= validator::make($data,$rule,$message);
if($validator->fails()){
return redirect() -> to('adduser')->withErrors($validator);
}else{
$tambah = new Admin();
$tambah->username = $request['username'];
$tambah->password = Hash::make($request['password']);
$tambah->email = $request['email'];
$tambah->alamat = $request['alamat'];
$tambah->lebih = $request['lebih'];
$tambah->save();
return redirect()->to('users')->with('success','Your Data Has Been Added');
}
}
and here is
my database table
i have use Hash for encrypt password, and i think nothing wrong with regist, what do i miss?
i keep having "not match" as the answer from this
please help master
By default, Laravel uses User model for authentication. You can customize it by editing config/auth.php:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],

How to pass in user id into foreach loop?

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 :)

Resources