set permission to role spatie/laravel-permission - laravel

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

Related

Sending images through Laravel Guzzle Client

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!!

Laravel error: (1/1) ErrorException count(): Parameter must be an array or an object that implements Countable

I'm trying to update data from my website to the database but I have the error given in the title.
Part of my Controller:
$user = auth()->user();
$count = count($request->get('alt_rs','alt_ci','linkrs'));
// On recupere les données de la BDD dans la variable $data
for($i = 0 ; $i < $count ; $i++) {
$data = [
'nom' => $request->get('nom'),
'prenom' => $request->get('prenom'),
'date_de_naissance' => $request->get('date_de_naissance'),
'job' => $request->get('job'),
'adresse' => $request->get('address'),
'code_postal' => $request->get('code_postal'),
'ville' => $request->get('ville'),
'telephone' => $request->get('phonenumber'),
'accroche' => $request->get('accroche'),
'email' => $request->get('email'),
'permis_b' => $request->get('permis'),
'photo_profil' => '../public/img/'. $filename,
'password' => $request->get('password'),
'logo_rs' => '../public/img/'. $filename,
'logo_ci' => '../public/img/'. $filename,
'description_ci' => $request->get('altci')[$i],
'description_rs' => $request->get('altrs')[$i],
'url' => $request->get('linkrs')[$i],
];
View example:
#foreach ($contact_info as $contact)
<label for="logo_rs">
<input type="file" id="logo_rs" name="logo_rs[]" accept="image/png, image/jpeg" >
</label>
<label for="linkrs">
<input type="text" placeholder="lien réseau social" name="linkrs[]" id="linkrs" value="{{$contact['url']}}">
</label>
<label for="altrs">
<input type="text" name="altrs[]" placeholder="Descriptif" id="altrs" value="{{$contact['description_rs']}}">
</label>
<br>
#endforeach
What can I do to resolve this?
The request->get('a','b','c') you are using is not returning an array. Try putting all the data you need in an array before using the count function. Something like:
$countable[] = request->get('a');
The parameter of the count() function must be iterable (array,object)
Problem resolved i just had to choose one thing in $count
$count = count($request->get('alt_rs','alt_ci','linkrs'));
became
$count = count($request->get('linkrs'));

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 validation throwing route error

I am attempting a basic validation check on form fields in the controller. The code is below:
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
The parameter passed to Redirect::to here is the folder members and registration view which resides in it. The problem is being caused by this line specifically:
return Redirect::to('members.registration')->withErrors($validator);
When it is commented out, form submission returns a blank white page. Otherwise the following error in the picture is shown
The route file has the following content:
Route::get('/', 'MainController#index');
Route::get('membersaccess', array('as' => 'membersaccess', 'uses' => 'MainController#loadMembersAccess'));
Route::get('signin', array('as' => 'signin', 'uses' => 'MembersController#loadlogin'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController#loadRegistration'));
Route::post('postLogin', array('as' => 'postLogin', 'uses' => 'MembersController#login'));
Route::post('postRegistration', array('as' => 'postRegistration', 'uses' => 'MembersController#registration'));
function containing the validation part is:
public function registration()
{
$email = Input::get('email');
$password = md5(Input::get('password'));
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
//echo $email;
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
}
and the form for reference:
#if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<h3> {{ $errors->first('email') }}</h3>
#endif
{{ Form::open(array('route' => 'postRegistration')) }}
{{ Form::text('email', null, array('placeholder'=>'Email', 'class' => 'randomfieldsize' ) ) }}
{{ Form::password('password', array('placeholder'=>'Password', 'class'=>'randomfieldsize' ) ) }}
{{ Form::text('firstname', null, array('placeholder'=>'First Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::text('lastName', null, array('placeholder'=>'Last Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::select('country', array('' => '', 'saudi' => 'Saudi Arabia', 'uae' => 'UAE')) }} <br><br>
{{Form::submit('Proceed', ['class' => 'button [radius round]'])}}
{{ Form::close() }}
Try this:
return Redirect::route('signup')->withErrors($validator);
You have no route defined as members.registration, so that may be the problem.
To show errors I usually use this (styling with bootstrap):
#if( $errors->has() )
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<ul>
#foreach ( $errors->all('<li>:message</li>') as $error )
{{ $error }}
#endforeach
</ul>
</div>
#endif
Edit: Ugh, didn't noticed it before, but your validation code is wrong. Please refer to http://laravel.com/docs/validation It should be something like this:
$email = Input::get('email');
$password = Input::get('password'); // Better to hash the password in another place, since md5 can create a hash even of an empty string. Also, please use laravel hash utility instead of md5: http://laravel.com/docs/security#storing-passwords
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
$validator = Validator::make(
compact('email', 'password', 'firstName', 'lastName', 'country'),
array(
'email' => 'required|min:7',
'password' => 'required|min:7'
'firstName' => 'required'
'lastName' => 'required'
));

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