I am trying to add drop down box information:
USERNAME EMAIL ROLE
3 user user#mail.com 12345
How to add role so that it shows administrator or Manager? instead of the codes?
models/Mpages.php
public function add_user()
{
$options = [
'roles' => 'administrator',
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => $hash,
'role' => form_dropdown('roles', $options, 'administrator')
);
return $this->db->insert('login', $data);
}
controllers/Cpages.php
public function addusers() {
$data['successmessage'] = "";
$data['options'] = array(
'administrator' => 'Administrator',
'manager' => 'Manager',
);
$this->Mpages->add_user();
$this->load->view('addusers', $data);
}
Here is the answer key:
controllers/Cpages.php
public function addusers() {
$data['successmessage'] = "";
$data['options'] = array(
'administrator' => 'Administrator',
'manager' => 'Manager',
);
$this->Mpages->add_user();
$this->load->view('addusers', $data);
}
models/Mpages.php
public function add_user()
{
$options = [
'roles' => 'administrator',
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => $hash,
'role' => $this->input->post('roles')
);
return $this->db->insert('login', $data);
}
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
I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.
Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
I have a textarea where a user can bulk add clients. In the textarea they would add the clients like this
client 1,client1#domain.com,client username 1
client 2,client2#domain.com,client username 2
client 3,client3#domain.com,client username 3
Here is what I have so far
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$name = $split_row[0];
$email = $split_row[1];
$username = $split_row[2];
$validate = Validator::make($email, [
$email => 'email',
$username => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
What I would like to know is how can I validate that $email is an email or that $username is unique.
The first param of Validator::make should be an array and the second is the rules for the keys of the array.
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$client['name'] = $split_row[0];
$client['email'] = $split_row[1];
$client['username'] = $split_row[2];
$validate = Validator::make($client, [
'email' => 'email',
'username' => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
You find all available rules in the docs:
$validate = Validator::make([ 'email' => $split_row[1],
'username' => $split_row[2]
], [
'email' => 'string',
'username' => 'unique:App\User,username'
]);
However, for email, I would rather check if its a valid email instead of a string. Thus,
'email' => 'email'
would be recommended.
I would suggest using the validator for the whole array instead of validating it row by row:
$clients = Str::of(request()->get('bulk_clients'))
->explode("\n")
->map(fn ($value) => Str::of($value)->explode(','))
->toArray();
$validator = Validator::make(compact('clients'), [
'clients' => 'array',
'clients.*.0' => 'required|string',
'clients.*.1' => 'required|email',
'clients.*.2' => 'required|unique:App\User,username',
]);
public function update(Request $request, $emp_id)
{
$validator = Validator::make($request->all(), [
'emp_code' => 'required|max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'emp_image' => 'required|image|mimes:jpeg,jpg,png,PNG,JPEG,JPG|max:2048',
'department' => 'required|max:255',
'designation' => 'required|max:255',
'joining_date' => 'required|max:255',
'offer_letter' => 'required|mimes:doc,docx,pdf,DOC,DOCX,PDF|max:2048',
'emp_email' => 'required|email|max:255|unique:employees',
'mobile_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
]);
$employeeimg = rand() . '.' . request()->emp_image->getClientOriginalExtension();
request()->emp_image->move(public_path('images'), $employeeimg);
$offerletter = rand() . '.' . request()->offer_letter->getClientOriginalExtension();
request()->offer_letter->move(public_path('docs/new'), $offerletter);
$form_data = array(
'emp_code' => $request->emp_code,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'emp_image' => $employeeimg,
'department' => $request->department,
'designation' => $request->designation,
'joining_date' => $request->joining_date,
'offer_letter' => $offerletter,
'emp_email' => $request->emp_email,
'mobile_number' => $request->mobile_number,
);
$data = Employee::findOrFail($emp_id);
//dd($form_data);
$data->update($form_data);
return redirect('employee')->with('msg_success', 'Employee updated successfully!');
}
I had getting error while updating the form with file uploads. and the error is
Call to a member function getClientOriginalExtension() on null
please give a solution for this
First, you need to check-in request has to file.
if($request->hasFile('emp_image')){
if (Input::file('emp_image')->isValid()) {
#unlink(IMG_PATH_URL.( $records->emp_image) );
$file = Input::file('emp_image');
$ext = $file->getClientOriginalExtension();
$mainFilename1 = rand().'.'.$ext;
$file->move(public_path('images'), $mainFilename);
}
}
if($request->hasFile('offer_letter')){
if (Input::file('offer_letter')->isValid()) {
#unlink(IMG_PATH_URL.( $records->offer_letter) );
$file = Input::file('offer_letter');
$ext = $file->getClientOriginalExtension();
$mainFilename2 = rand().'.'.$ext;
$file->move(public_path('docs/new'), $mainFilename);
}
}
Make sure You have added the enctype in form
<form action="" method="post" enctype="multipart/form-data">
</form>
Your controller should be like:
public function update(Request $request, $emp_id)
{
$validator = Validator::make($request->all(), [
'emp_code' => 'required|max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'emp_image' => 'required|image|mimes:jpeg,jpg,png,PNG,JPEG,JPG|max:2048',
'department' => 'required|max:255',
'designation' => 'required|max:255',
'joining_date' => 'required|max:255',
'offer_letter' => 'required|mimes:doc,docx,pdf,DOC,DOCX,PDF|max:2048',
'emp_email' => 'required|email|max:255|unique:employees',
'mobile_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
]);
$data = Employee::findOrFail($emp_id);
if($data){
$data->emp_code = $request->emp_code;
$data->first_name = $request->first_name;
$data->last_name = $request->last_name;
$data->department = $request->department;
$data->designation = $request->designation;
$data->joining_date = $request->joining_date;
$data->emp_email = $request->emp_email;
$data->mobile_number = $request->mobile_number;
if($request->hasFile('emp_image')){
if (Input::file('emp_image')->isValid()) {
#unlink(IMG_PATH_URL.( $records->emp_image) );
$file = Input::file('emp_image');
$ext = $file->getClientOriginalExtension();
$mainFilename1 = rand().'.'.$ext;
$file->move(public_path('images'), $mainFilename);
$data->emp_image => $mainFilename1;
}
}
if($request->hasFile('offer_letter')){
if (Input::file('offer_letter')->isValid()) {
#unlink(IMG_PATH_URL.( $records->offer_letter) );
$file = Input::file('offer_letter');
$ext = $file->getClientOriginalExtension();
$mainFilename2 = rand().'.'.$ext;
$file->move(public_path('docs/new'), $mainFilename2);
$data->offer_letter => $mainFilename2;
}
}
if( $data->save() ) {
return redirect('employee')->with('msg_success', 'Employee updated successfully!');
}
}
}
public function update(Request $request, $emp_id)
{
$validator = Validator::make($request->all(), [
'emp_code' => 'required|max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'emp_image' => 'required|image|mimes:jpeg,jpg,png,PNG,JPEG,JPG|max:2048',
'department' => 'required|max:255',
'designation' => 'required|max:255',
'joining_date' => 'required|max:255',
'offer_letter' => 'required|mimes:doc,docx,pdf,DOC,DOCX,PDF|max:2048',
'emp_email' => 'required|email|max:255|unique:employees',
'mobile_number' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
]);
$emp_img = $request->file('emp_image');
$employee = rand() . '.' . $emp_img->getClientOriginalExtension();
$emp_img->move(public_path('images'),$employee);
$offer_letter = $request->file('emp_image');
$offer = rand() . '.' . $offer_letter->getClientOriginalExtension();
$offer_letter->move(public_path('docs/new'),$offer);
$form_data = array(
'emp_code' => $request->emp_code,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'emp_image' => $employee,
'department' => $request->department,
'designation' => $request->designation,
'joining_date' => $request->joining_date,
'offer_letter' => $offer,
'emp_email' => $request->emp_email,
'mobile_number' => $request->mobile_number,
);
$data = Employee::findOrFail($emp_id);
//dd($form_data);
$data->save($form_data);
return redirect('employee')->with('msg_success', 'Employee updated successfully!');
}
and in view form
you have to add
<form action="" method="" enctype="multipart/form-data">
I Hope It Will Help You
RegisterController.php
I added here an update function so that when the user wants to login with Facebook, he/she will be redirected to a form and then fill the fields so that their information will be stored in the Database.
protected function create(array $data)
{
if ($data['userEmail']) {
return User::where('email', $data['userEmail'])
->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
return User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
}
The error when the IF statement returns true is this
"Type error: Argument 1 passed to
Illuminate\Auth\SessionGuard::login() must implement interface
Illuminate\Contracts\Auth\Authenticatable, integer given, called in
C:\xampp\htdocs\esoftwaredeals\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 35".
However, if it returns false, there will be no error and a new user is created and will automatically redirect to the "/my-account" page which is where I wanted to redirect when the user successfully updated their information.
You need to return User instance from the create() method:
protected function create(array $data)
{
if ($data['userEmail']) {
$user = User::where('email', $data['userEmail'])->first();
$user->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
$user = User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
return $user;
}
Also, you should use the updateOrCreate() method to keep the code maintainable. For example:
protected function create(array $data)
{
$data['password'] = bcrypt($data['password']);
return User::updateOrCreate(
array_only($data, ['email', 'full_name']),
array_except($data, ['email', 'full_name'])
);
}
An update query returns the number of rows that where affected by the update query.So when the update user is successful it will return 1.
The create method returns the saved model instance. So this is causing the issue in your code.
You can use find and save method provided by eloquent and return the user object in if statement and it will work.
$user = User::where('email', $email)->first();
$user->firstname = $firstname;
$user->lastname = $lastname;
$user->save();
return $user;
Try like this and it should work.
$user = User::find($usuario->ID);
$user->rol_id = 1;
$user->save();
}
}
}
return view('dashboard.index')->with(compact('cantReferidosDirectos', 'cantReferidosIndirectos', 'cantReferidosActivos', 'fechaProxActivacion', 'new_member',
'cantventas', 'cantventasmont', 'fullname', 'rangos', 'cantAllUsers', 'rankingComisiones', 'rankingVentas', 'permiso','noticias', 'contTicket', 'moneda',
'nombreRol'
));
}
/**
* Permite actualizar las informacion de los usuarios
*
* #access public
* #return view
*/
public function ActualizarTodo()
{
$comisiones = new ComisionesController;
$comisiones->ObtenerUsuarios();
$todousers = $this->generarArregloUsuario(Auth::user()->ID);
foreach ($todousers as $user ) {
if ($user['rol'] != 0) {
$activacion = new ActivacionController;
$activacion->activarUsuarios($user['ID']);
}
}
Arguments
"compact(): Undefined variable: fechaProxActivacion"
Como soluciono este error