Laravel: how to update records values coming as arrow - laravel

I am new to Laravel and I need to update records coming as array from a form.
$a = $request->id;
$b = $request->val;
Now I need to update the records
Details::find($b)->update(['detail'=>$a]);
The script above obviously does not work...

You can do it in more than one way, try this :
$details = Details::find($request->input($id));
$details->val = $request->input('val');
$details->save();
Or you can use this if the inputs has the same name as the model fields:
$details = Details::findOrFail($request->input($id));
$details->update($request->all());

You can update in the following ways. Assuming detail is your field name to update.
$id = $request->id;
$val = $request->val;
$detail = Details::findOrFail($id);
$detail->detail = $val;
$detail->save();
For the below to work. You need to set the $fillable propery in the model
// In Detail model
protected $fillable = ['detail'];
// Controller
Details::where('id', $id)->update([
'detail' => $val
]);

$a = $request->id;
$b = $request->val;
$detail = Detail::where('id', $a)->first();
$detail->update(['detail' => $b]);

Related

Foreach loop is showing error while storing multiple id's

I am creating a group and also storing users id's in it but its showing error in foreach loop i.e. Invalid argument supplied for foreach().
Here is my controller code :
public function createGroup(Request $request)
{
$user_id = request('user_id');
$member = request('member');
$data = array(
'name'=>$request->name,
);
$group = Group::create($data);
if($group->id)
{
$resultarr = array();
foreach($member as $data){
$resultarr[] = $data['id'];
}
$addmem = new GroupUser();
$addmem->implode(',', $resultarr);
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
return $this->sendSuccessResponse([
'message'=>ResponseMessage::statusResponses(ResponseMessage::_STATUS_GROUP_SUCCESS)
]);
}
}
I am adding values like this,
Desired Output,
I just want that each member to store with different id's in table and group id will be same.
Please help me out
Avoid that if check, it does absolute nothing.
if($group->id)
Secondly your input is clearly a string, explode it and you will have the expected results. Secondly don't save it to a temporary variable, create a new GroupUser immediately.
foreach(explode(',', $member) as $data){
$addmem = new GroupUser();
$addmem->user_id = $data;
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
}
That implode line makes no sense at all, i assumed there is a user_id on the GroupUser relation.
u need to send array from postman
like
Key | value
member[] | 6
member[] | 3
or
$memberArray = explode(",", $member = request('member'))
if($group->id)
{
$resultarr = array();
foreach($memberArray as $data){
$resultarr[] = $data['id'];
}
$addmem = new GroupUser();
$addmem->implode(',', $resultarr);
$addmem->group_id = $group->id;
$addmem->status = 0;
$addmem->save();
return $this->sendSuccessResponse([
'message'=>ResponseMessage::statusResponses(ResponseMessage::_STATUS_GROUP_SUCCESS)
]);
}

Call to a member function storeAs() on null

I want to store images with id to table and save them to a folder.
I have two tables catalogs and images.Images table has img_id which is a foreign key to id in catalogs table, code in my controller is:
$catalog = new Katalog();
$catalog->name = $name;
$catalog->picturePath = $name . '/';
$catalog->description = $desc;
$catalog->address = $request->input('address');
$catalog->phone_number = $request->input('phone_number');
$catalog->email = $request->input('e_mail');
$catalog->info_holder = $request->input('type');
$catalog->partner_logo = $logo_img_name;
$catalog->short_news = $request->input('short_news');
$catalog->updated_at = Carbon::now();
$catalog->site = $request->input('site');
$catalog->creator_id = Auth::user()->id;
$catalog->save();
$id = Katalog::where('name', $name)->first()->id;
if ($request->hasFile('images')) {
foreach ($request->file('images') as $image) {
$img_name = $image->getClientOriginalName();
$request->image->storeAs(('/images/' . $name), $img_name, 'images');
Image::creat([
'img_id' => $id,
'img_name' => $img_name
]);
}
}
After storing data to the catalogs table it returns a new id but I want to store images to images table with returned id but can not do this.Error shows here $request->image->storeAs(('/images/' . $name), $img_name, 'images');
Help me please thanks in advance.
You can get the ID from the just created object (Katalog) without a query
$id = $catalog->id;
instead of
$id = Katalog::where('name', $name)->first()->id;
Because if there are other Katalog records with the same name, you may not get the one you want
PS: you may have a typo here, add an "e" at the end
Image::create([
'img_id' => $id,
'img_name' => $img_name
]);
Hope this helps

Laravel : How can i get old and new value by updateOrCreate

I want update or create in data base
but i want get the old value and updated value because i want to compare between these two value
for example
this item in table user
name = Alex and Order = 10
so now i want update this person by
name = Alex and Order = 8
Now After updating or creating if not exist
just for update i want get
Old order 10 | And new Order 8
I want compare between these order
i have tryin getChange() and getOriginal() but two the function give me just the new value.
Please Help
You can get the old value using getOriginal if you have the object already loaded.
For example :
$user = User::find(1);
$user->first_name = 'newname';
// Dumps `oldname`
dd($user->getOriginal('first_name'));
$user->save();
However in case of updateOrCreate, you just have the data. I am not sure about a way to do it using updateOrCreate but you can do simply do :
$user = User::where('name', 'Alex')->first();
$newOrder = 10;
if($user){
$oldOrder = $user->getOriginal('order');
$user->order = $newOrder;
$user->save();
}
Is the name unique in the table? Because if it is not you will have updates on multiple rows with the same data.
So the best approach is to use the unique column which is probably the ID.
User::updateOrCreate(
[ 'id' => $request->get('id') ], // if the $id is null, it will create new row
[ 'name' => $request->get('name'), 'order' => $request->get('order') ]
);
Solution
$model = Trend::where('name', $trend->name)->first();
if ($model) {
$model->old_order = $model->getOriginal('order');
$model->order = $key + 1;
$model->save();
} else {
Trend::where('order', $key + 1)->delete();
$new = new Trend();
$new->name = $trend->name;
$new->old_order = $key + 1;
$new->order = $key + 1;
$new->tweet_volume = $trend->tweet_volume;
$new->save();
}

laravel retrieve json and save into database

I am getting cinema title + times using API from Cinelist, I then want to save these values into a database.
At the moment, it does save but only 1 record, the last one. However, I want it to save each one.
Also each time it is run I want to update existing records instead of creating new ones unless there are more results.
So usually there are 5 records, each time I run the function I want to update the database with the new 5 records, however, if it's a different day and there are 6 records I want to update 5 records and insert 1 extra one so there is 6.
My code so far:
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
$id = + 1;
$films = Film::where('id', $id)->first();
if (!$films) {
$films = new Film();
}
$films->title = $title;
$films->times = $time;
$films->save();
}
}
You may use eloquent's updateOrCreate method to insert non-existent data and update existing data.
function odeon(){
$data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565');
$data = json_decode($data);
foreach($data->listings as $listing){
$title = $listing->title;
$time = implode(', ', $listing->times);
Films::updateOrCreate([
'title' => $title,
'$times' => $time
]);
}
}

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

Resources