Is there a way that I can update a form input using something like insert_id?
I have a form for adding factories to a table and I use the insert_id to store the factories id in another table too after submit.
this all works great, but is there such a way for $this->db->update?
My model for updating:
function updatebedrijf($id, $data)
{
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
}
My controller function for updating:
function updatebedrijven()
{
$dbres = $this->db->get('categorieen');
$ddmenu = array();
foreach ($dbres->result_array() as $tablerow) {
$ddmenu[$tablerow['idcategorieen']] = $tablerow['Categorie'];
}
$data['opties'] = $ddmenu;
$data['info'] = $this->members_model->getbedrijf($id);
$data['id'] = $this->uri->segment(3);
$this->load->view('members/header');
$this->load->view('members/editform', $data);
$this->load->view('members/footer');
}
for adding factories i use this with insert_id:
controller:
function addbedrijven()
{
$this->members_model->addbedrijf();
redirect('members/index');
}
model:
function addbedrijf()
{
$data1 = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
'logo' => $this->input->post('logo')
);
$this->db->insert('bedrijven',$data1);
if($this->db->affected_rows() >= 1)
{
$to_bedrijfcategorieen['idbedrijven'] = $this->db->insert_id();
$to_bedrijfcategorieen['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat($to_bedrijfcategorieen);
}else{
return FALSE;
}
}
function insert_bedrijfcat($data1)
{
$this->db->insert('bedrijfcategorieen', $data1);
return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
}
Hope it's clear enough.
Related
I currently use Laravel 8 and I want to know how do I ignore unique validation when a user is updating their profile? If the user is updating every field except the pageName I don't want it to throw a vaildation error cause the user is already the owner of that pageName. I tried this code but it gives error: ErrorException
Undefined variable: user
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Auth;
use DB;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
$links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();
return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show buttons for add link
public function showButtons()
{
$data['buttons'] = Button::select('name')->get();
return view('studio/add-link', $data);
}
//Save add link
public function addLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required'
]);
$link = $request->link;
$button = $request->button;
$userId = Auth::user()->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
$links = new Link;
$links->link = $link;
$links->user_id = $userId;
$links->button_id = $buttonId;
$links->save();
return back()->with('message', 'Link Added');
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$link = $request->link;
$linkId = $request->id;
if(empty($link && $linkId))
{
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
return redirect()->away($link);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
return back();
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if($upLink == 'yes'){
$up = 'no';
}elseif($upLink == 'no'){
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$buttons = Button::select('name')->get();
return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required',
]);
$link = $request->link;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(request $request)
{
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$profilePhoto = $request->file('image');
$pageName = $request->pageName;
$pageColor = $request->pageColor;
$pageFontcolor = $request->pageFontcolor;
$pageDescription = $request->pageDescription;
$pagePixiv = $request->pagePixiv;
User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);
if(!empty($profilePhoto)){
$profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
}
return back()->with('message', 'Saved');
}
//Show user (name, email, password)
public function showProfile()
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);
return back();
}
}
Anyone know how to fix this?
You can change your code to the following
$userId = Auth::user()->id;
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name,'.$userId,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
you can use the Rule object to make that validation:
'pageName' => ['nullable','alpha_dash', Rule::unique('users','littlelink_name')->ignore($user->id)
this is the function, the error is in line 25 in
'$data = Excel::load($path)->get();' saying that None-Static méthode 'load' should not be called statically:
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'zi' => $row['zi'],
'siteId' => $row['siteId'],
'gsmId' => $row['gsmId'],
'topoCont' => $row['topoCont'],
'plannRedr' => $row['plannRedr'],
'Country' => $row['country'],
'dateReal' => $row['dateReal'],
'semReal' => $row['semReal'],
'statuts' => $row['country'],
);
}
}
if(!empty($insert_data))
{
DB::table('tbl_customer')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
}
add this in your controller :
use Maatwebsite\Excel\Facades\Excel;
I can't update data in a database.i don't know what happend.please help me. Display data Press the edit button.But i can not edit data on the database.
I have posted the code below:
Controller.php
public function ajax_update()
{
$data = array(
'placename' => $this->input->post('placename'),
'description' => $this->input->post('description'),
'tel' => $this->input->post('tel'),
'latitude' => $this->input->post('latitude'),
'longtitude' => $this->input->post('longtitude'),
'placetype_id' => $this->input->post('placetype_id'),
'province_id' => $this->input->post('province_id'),
);
$this->tblplace->update(array('placeid' => $this->input->post('placeid')), $data);
echo json_encode(array("status" => TRUE));
}
Modal.php
public function save($data)
{
$this->db->insert('tblplace', $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update('tblplace', $data, $where);
return $this->db->affected_rows();
}
I can get data from the database to show in the textbox. But can't update data.I need to help.Thank you.
Your Controller:
public function ajax_update()
{
//You should also check the post array.
$ajax_post_data = $this->input->post();
log_message('debug', 'Ajax Post Data Array:' . print_r($ajax_post_data, TRUE));
$placeid = $this->input->post('placeid');
$data = array(
'placename' => $this->input->post('placename'),
'description' => $this->input->post('description'),
'tel' => $this->input->post('tel'),
'latitude' => $this->input->post('latitude'),
'longtitude' => $this->input->post('longtitude'),
'placetype_id' => $this->input->post('placetype_id'),
'province_id' => $this->input->post('province_id'),
);
$this->load->model('tblplace');
$updte_status = $this->tblplace->update($placeid, $data);
if($updte_status == TRUE){
echo json_encode(array("status" => true));
} else {
echo json_encode(array("status" => false));
}
}
In Model:
public function update($where, $data)
{
$this->db->where('id', $where)
->update('tblplace', $data);
log_message('debug', 'Last Update Query:' . print_r($this->db->last_query(), TRUE));
log_message('debug', 'Affected row count:' . print_r(count($this->db->affected_rows()), TRUE));
if ($this->db->affected_rows() === 1) {
return TRUE;
}else{
return FALSE;
}
}
Hope this is clear and it will help you to update the data.
There is no where condition in your update function
public function update($where, $data)
{
$this->db->where($where);
$this->db->update('tblplace', $data);
return $this->db->affected_rows();
}
I'm trying to use ignore method in laravel to apply validation on updating profile I have use ignore() for this but looks like I have gone somewhere wrong and ended up with this error can you help me out to find this here is my code. Thanks for your insights :)
User Controller
public function editProfile(Request $request) {
$userId=$request->userId;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator =Validator::make($request->all(), [
'phoneNumber' => [
'max:10',
Rule::unique('users')->ignore($userId,'userId'),
],
]);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
}
Check if you specifying the correct key for the unique check. Your code says userId is the primary key to compare the given id with, is this correct? If the key is 'id' by default then you can ignore the parameter.
Rule::unique('users')->ignore($$request->userId),
'phoneNumber' => 'max:10|unique:users,id,'.$request->userId,
well after the hell of time spent I finally got the answer.
public function editProfile(Request $request) {
$userId=$request->userid;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator = Validator::make(
array(
'phoneNumber' => $phoneNumber,
),
array(
'phoneNumber' =>'size:10', Rule::unique('users')->ignore($request->userId, 'userId'),
)
);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}
In my model I have return below function for get record id
function getLastInserted()
{
$query = $this->db->select("MAX(`UserID`)+1 as userid")->get("registeration");
return $query->result();
}
Now I want to pass that ID to mycontroller for record insertion
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
Now I want to access model function in controller and pass record id in data function How I do ??
set return in model and in controller write
$insert_id=$this->db->insert_id();
In Controller load your model first using
$this->load->model('model_name');
Then call to model's getLastInserted() function.
$ID = $this->model_name->getLastInserted();//you will get id here
In model return $query->row()->userid; insead return of $query->result().
Then modify the controller:
public function newregistration()
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $this->model_name->getLastInserted(),
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}
hi i worked out the solution on last inserted id dear here the code:
controller:
function sample() {
$sid=$this->adminmodel->getLastInserted();
$this->adminmodel->newregistration( $sid);
}
model:
function getLastInserted()
{
$query = $query = $this->db->select('id')->order_by('id','desc')->limit(1)->get('employee_outs')->row('id');
return $query;
}
model:
public function newregistration($sid)
{
if ($this->form_validation->run())
{
$data = array(
'UserID'=> $sid,
'Name' => $this->input->post('Name'),
'MobileNo' => $this->input->post('MobileNo'),
'IMEINumber' => $this->input->post('IMEINumber'),
'City' => $this->input->post('City')
);
$this->adminmodel->insertregistration($data);
}
}