Sending images through Laravel Guzzle Client - laravel

I am trying to upload multiple images using guzzlehttp client. I load images as a file and loads only one image with the code below.
$clientPAimages = new Client();
$imagesPA = Req::file('images');
foreach($imagesPA as $image){
$bodyImages[] = [
'name' => 'image',
'contents' => fopen($image->getRealPath(), 'r'),
'filename' => $image->getClientOriginalName(),
'headers' => [
'Content-Type' => '<Content-type header>'
]
];
}
$responsePA3 = $clientPAimages->request('POST', 'link/images', [
'multipart' => $bodyImages
]);
$responsePA3->getBody();
Does anyone have any idea how to solve this i.e. how to save multiple images?

I was in this kind of situation, when i needed to send multiple images from the laravel app to the node.js app. Your code seems ok, but may you've something wrong in your blade, for example usage of enctype="multipart/form-data" in the form, or name="images[]" as an input property, or something like that.
Anyway i'll share here the snippet, which worked well for me before, so i guess it can be useful.
Specifications for this snippet was:
"laravel/framework": "^8.12",
"guzzlehttp/guzzle": "^7.0.1",
create.blade.php
<form action="http://internal.site/upload" method="post" enctype="multipart/form-data">
#csrf
<input id="ss_images"
name="images[]"
type="file"
multiple="multiple"
class="input"
accept=".jpeg,.bmp,.png,.jpg,.gif"
/>
<div class="mt-3">
<label class="{{ $errors->has('name') ? 'has-error' : '' }}">
{{ $errors->has('name') ? $errors->first('name') : "Name" }}
</label>
<input value="{{ old('name') }}" type="text" class="input" placeholder="Name" name="name">
</div>
<div class="mt-3">
<label class="{{ $errors->has('description') ? 'has-error' : '' }}">
{{ $errors->has('description') ? $errors->first('description') : "Description" }}
</label>
<textarea class="input" placeholder="Description" name="description">{{ old('description') }}</textarea>
</div>
</form>
ItemController.php
use GuzzleHttp\Client;
// ...
public function upload(Request $request)
{
$data = $request->only([
'name',
'description',
]);
$multipart = [];
if($request->hasFile('images')) {
foreach ($request->file('images') as $k => $image) {
$multipart[] = [
'name' => 'file',
'contents' => fopen($image->getRealPath(), 'r'),
// ... some additional fields
];
}
}
// adding some text-oriented data if need
$multipart[] = [
'name' => 'data',
'contents' => json_encode($data, true),
];
$client = new Client();
$url = "http://external.site/link/images";
$response = $client->request('POST', $url, [
'multipart' => $multipart
]);
$res_json = $response->getBody()->getContents();
$res = json_decode($res_json, true);
return redirect()->back()->with([
'success' => $res['success'],
'flash_message' => $res['message'],
]);
}
Enjoy!!

Related

set permission to role spatie/laravel-permission

I'm trying to use this library and set permission to my users. I'm reading documentation and I created my roles. I set my array in input with name.
#foreach ($allPermission as $permission)
<div class="col-md-2">
<label class="form-check-label mr-4" for="{{ $permission->id }}">{{ $permission->name }}</label>
<input class="form-check-input" name="permission[]" type="checkbox" id="{{ $permission->id }}" value="{{ $permission->name }}">
</div>
#endforeach
In my controller, I received this:
Array ( [0] => show [1] => create [2] => destroy )
I'm trying to set this permissions with this:
$user = User::where("id", $id)->update([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => \Hash::make($request->get('password')),
]);
// update permissions to user
$user->givePermissionTo($request->get('permission'));
this returns...
Call to a member function givePermissionTo() on int
I'm trying to set permissions with id and with name and getting same error.
$user = User::where("id", $id)->update([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => \Hash::make($request->get('password')),
]);
return $user is count records was updated ($user of you is not a collection)
you can use :
$user = User::find($id);
then
$user->givePermissionTo($request->get('permission'));

How to validate a JSON Request object in laravel validation?

How will I validate the current entries from here , this is the json response inside the Chrome Devtools after submitting the form thru axios ?
And this is in my UpdateProfileRequest.php
public function rules()
{
return [
'username' => 'required|unique:users|min:3',
'password' => 'required|min:8|confirmed',
'confirm_password' => 'required|',
'current_password' => 'required|u',
'country_id' => 'required|integer',
'display_name' => 'required|min:5',
'email' => 'required|unique:users,email_address',
'phone_number' => 'required|alpha_num',
'image' => 'mimes:jpg,png,gif'
];
This is the whole response from the request
This is inside my UpdateProfile.vue
<div>
<div v-if="user != null">
<form class="bg-white m-auto h-full p-4 w-full" id="setup-billing-form" #submit.prevent="submitProfile()" method="POST">
<div class="flex inline-block">
<div id="input-group" class="w-3/5">
<label for="name" class="block uppercase tracking-wide text-black-v2 text-xs font-bold mb-2">Username
</label>
<input v-model="form.username" type="text" class="hover:bg-grey-lightest bg-grey-lighter w-full mb-2 p-2 leading-normal" id="pin" name="pin" autocomplete="name" placeholder="Your Username" required>
</div>
<div id="input-group" class="ml-2 w-3/5">
<label for="name" class="block uppercase tracking-wide text-black-v2 text-xs font-bold mb-2">Email
</label>
this is is inside my axios request
submitProfile(){
let data = new FormData();
axios.put(this.endpoint, {
form : this.form ,
image : this.image
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
},
Now, I want to ask if how do I validate those requests inside my UpdateProfileRequest, should I add the form. to each of those requests ?
Two Methods:
1. just use form.username to validate
$rule = [
'form.username' => 'required|unique:users|min:3',
'form.password' => 'required|min:8|confirmed',
'form.confirm_password' => 'required|',
'form.current_password' => 'required|u',
'form.country_id' => 'required|integer',
'form.display_name' => 'required|min:5',
'form.email' => 'required|unique:users,email_address',
'form.phone_number' => 'required|alpha_num',
'image' => 'mimes:jpg,png,gif'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
}
2. Flatten the object to request:
It seems that you new a formdata without using it.
And pass the data with keys form and image.
You need to flatten your object before put it:
submitProfile(){
// if you use formdata
// let form = new FormData(this.form);
// let form = form.append('image', this.image);
let form = Object.assign({}, this.form); // clone this.form
form['image'] = this.image;
axios.put(this.endpoint, form).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
},
This request that you can directly validate by
'username', 'password', ... without prefix form.
and if you want to insert the datas, you can just use $request->except('image').

Laravel checkbox validation, always empty?

I have a checkboxes like this:
<div class="form-group">
<div style="display:none ;" class="weekday_message form-control alert-warning"></div>
<label id="weekday2" for="weekday" class="col-md-4 control-label">Weekday</label>
<div class="required form-field" name="weekday" id="weekday">
<input class="weekday" type="checkbox" name="weekdays[]" value="MO">Monday
<input class="weekday" type="checkbox" name="weekdays[]" value="TU">Tuesday
<input class="weekday" type="checkbox" name="weekdays[]" value="WE">Wednesday
<input class="weekday" type="checkbox" name="weekdays[]" value="TH">Thursday
<input class="weekday" type="checkbox" name="weekdays[]" value="FR">Friday
<input class="weekday" type="checkbox" name="weekdays[]" value="SA">Saturday
<input class="weekday" type="checkbox" name="weekdays[]" value="SU">Sunday
</div>
<span class="help-block">
<strong></strong>
</span>
</div>
My validation:
public function rules()
{
return [
'startdate' => 'required|date',
'endate' => 'nullable|date',
'startime' => ['required', new Time],
'endtime' => ['required', new Time],
'title' => 'required',
'entity_id' => 'required',
'type' => 'required|exists:entities,type',
'description' => 'required',
'frequency' => 'required',
'interval' => 'nullable|numeric',
'monthday' => 'nullable|numeric|min:1|max:3',
'weekdays' => 'array|max:3',
'month' => 'nullable|numeric',
'until' => 'nullable|date',
'tags' => 'nullable',
];
}
and controller:
public function storeEvent(EventRequest $request)
{
$test = ($request->input('weekdays'));
dd($test);
$weekday_string = implode(",", $request->input('weekdays'));
$request->merge(array('weekday', $weekday_string));
dd($request->all());
$event = DirtyEvent::create($request->all());
$geoloc_id = Entity::find($event->entity_id)
->first();
$user_id = Auth::id();
// Save Geoloc + user id into newly created event
$event->_geoloc()->associate($geoloc_id);
$event->users()->associate($user_id);
$event->save();
Now, validation seems to pass because it does data dump, however both dd($test) as well as $request->all() are giving me back empty weekdays, like it would not be defined. What could be the possible cause of this?
If you want to make sure you have always at least one weekday selected you should change:
'weekdays' => 'array|max:3',
into:
'weekdays' => 'array|required|max:3',
Also I suppose you don't send data using standard HTML form because you set for example name for divs so maybe you forget to attach weekdays or have bug in code elsewhere?
Your HTML says weekday (singular) but your rules set says weekdays (plural).
There needs to be at least one checkbox selected to make the input weekdays to be included in the request. You can use a default value in case none was selected by adding a hidden input before the checkboxes.
<input type="hidden" name="weekdays" value="defaultValue">

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

laravel Undefined offset: 0

I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0
It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif
I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);
also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}

Resources