Payment preference, Mercadopago's SDK & Laravel 5.5 - laravel

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

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.

Livewire validateOnly with validate in the same component

I have a little problem with the data validation with livewire ( laravel ).
I noticed that when I set up the validation in real time ( validateOnly() ), the information entered in the form is validated in real time. At this level everything is fine.
But when I click on the button to submit the form (even though the form contains errors), the form is unfortunately sent to my function defined in the wire:submit.
So my question is : is it possible to revalidate the information in the wire:submit method that receives the data after the form is submitted ? If so, how can I do that?
PS: I tried to set the validate method in my wire:submit function but nothing happens. It blocks the form from being submitted but it doesn't give me an error .
My source code :
<?php
class UserProfile extends Component
{
use WithFileUploads;
public $countries = [];
public $profile = [];
protected function rules() {
if ( !LivewireUpdateProfileRequest::authorize() ) {
return abort(403, "Your are not authorized to make this request !");
}
$rules = LivewireUpdateProfileRequest::rules();
if ( !empty($this->profile['phone']) ) {
$rules['profile.phone'] = [ 'required', 'phone_number:' . $this->profile['phone'] ];
}
return $rules;
}
public function mount()
{
$this->countries = Countries::all();
$this->profile = Auth::user()->toArray();
}
public function updateUserProfile()
{
$validatedData = $this->validate();
dd( $validatedData );
}
public function updated($key, $value)
{
$this->validateOnly($key);
}
public function render()
{
return view('livewire.user-profile');
}
}
Html source :
<form action="" method="POST" wire:submit.prevent="updateUserProfile">
<input name="profile.email" type="email" wire:model="profile.email" />
#error('profile.email') {{ $message }} #enderror
<input name="profile.phone" type="tel" wire:model="profile.phone" />
#error('profile.phone') {{ $message }} #enderror
</form>
Here is LivewireUpdateProfileRequest content :
<?php
namespace App\Http\Requests\Web;
use Illuminate\Foundation\Http\FormRequest;
class LivewireUpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public static function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public static function rules()
{
return [
'profile' => ['required', 'array', 'size:10'],
'profile.firstname' => ['required', 'string'],
'profile.lastname' => ['required', 'string'],
'profile.email' => ['required', 'email'],
'profile.phone' => ['required', 'phone_number:33'],
'profile.gender' => ['required', 'gender'],
'profile.image' => ['sometimes', 'image', 'mimes:png,jpg,jpeg'],
'profile.address' => ['required', 'string'],
'profile.city' => ['required', 'string'],
'profile.country_id' => ['required', 'exists:countries,id'],
'profile.birth_at' => ['required', 'date', 'min_age:18'],
];
}
}
Usually in your saving method you would run validation once more for all fields. The livewire docs share this example:
Livewire Component:
class ContactForm extends Component
{
public $name;
public $email;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function saveContact()
{
$validatedData = $this->validate();
Contact::create($validatedData);
}
}
With this HTML:
<form wire:submit.prevent="saveContact">
<input type="text" wire:model="name">
#error('name') <span class="error">{{ $message }}</span> #enderror
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Save Contact</button>
</form>
This should validate the inputs near-realtime using the updated-method and on submit using the saveContact-method.
If you could share your code, we could debug it easier.
Source: https://laravel-livewire.com/docs/2.x/input-validation#real-time-validation

Laravel 5.8 send email with file attachment

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');

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