Helper,
I wanna update multiple addresses for a particular user_id, with out changing its existing order. Also I'm using relation here.
public function update(Request $request, $id){
$data['id'] = $id;
$user = User::with('addresses')->find($id);
$j = $user['addresses'][0]['id'];
foreach($request->address_id as $key => $i){
$i++;
}
foreach($request->address1 as $key => $v){
if($j<$i){
$user->addresses()->whereUserId($data['id'])->update([
'address1' => $v,
'address2' => $request->address2[$key],
'state' => $request->state[$key],
'country' => $request->country[$key]
]);
}
$j++;}
}
I'm getting input somewhat like this,
{"_method":"PATCH","address_id":["92","93"],"address1":["aaa","xxx"],"address2":["bbb","yyy"],"state":["ccc","zzz"],"country":["India","India"]}
When I do my update the last input, which means, xxx,yyy,zzz,India is getting update for both rows92,93
Related
I am trying to store logged user's id but I am getting this error
ErrorException
array_map(): Argument #2 should be an array
This is the code in the controller
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$data = request()->validate([
'id' => $id = Auth::id(),
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
The error is in this line of code.
'id' => $id = Auth::id(),
I know that should be a string but to explain to you what I am trying to do, and I still have not found any solution.
Do it Like this.
public function store(Request $request)
{
if (!auth()->check()) {
abort(403, 'Only authenticated users can create new posts.');
}
$request->validate([
'content' => 'required',
'topic' => 'required',
'hashtag' => 'required'
]);
$data = $request->all();
$data['id'] = Auth::id();
$check = Tweets::create($data);
return Redirect::to("form")->withSuccess('Great! Form successfully submit with validation.');
}
Delete this
'id' => $id = Auth::id(),
and add
$data['id'] = Auth::id();
before
$check = Tweets::create($data);
That should work
I’m working on laravel excel import. The data can be loaded using
$data = Excel::load($path)->get(); command. But, when i try to loop through $data object and put it in $insert[], some fields remaining empty.
my import function look like
public function import(request $request) {
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = [
'Item_name' => $value->Item_name,
'Manufacturer' => $value->Manufacturer,
'Serial_no' => $value->Serial_no,
'Model_no' => $value->Model_no,
'status' => $value->status,
'Price' => $value->Price,
'photo' => $value->photo,
'user_id' => $value->user_id,
'deletedBy' => $value->deletedBy,
'created_at' => $value->created_at,
'updated_at' => $value->updated_at,
];
}
if(!empty($insert)){
$insertData = DB::table('inventories')->insert($insert);
if ($insertData) {
Session::flash('success', 'Your Data has successfully imported');
}else {
Session::flash('error', 'Error inserting the data..');
return redirect()->back();
}
}
}
return redirect()->back();
}
when I dd($data); the result looks as
and the result of dd($insert); looks as
if any friend can help me that why some fields like Item_name, Manufacturer, and Serial_no remain null, would be appreciated.
solved!
all value->item_names must write in lowercase; I thought that it should match with the database table column names.
I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?
foreach($datas as $data){
DB::table('users')->updateOrInsert([
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
}
Check out [updateOrInsert] this documentation (https://laravel.com/api/6.x/Illuminate/Database/Query/Builder.html#method_updateOrInsert). You need two parameters. One is the matching attributes (i.e., the attributes you would use to identify your record in case it exists), the other is your array (the new values you wish to insert or update the record with).
updateOrInsert(array $attributes, array $values = [])
Example
DB::table('users')->updateOrInsert(
[
'user_connect_id' => $user->connect_id
],
[
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
There are two arguments in updateOrInsert method.The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs containing the columns to be updated.
For e.g :
DB::table('users')
->updateOrInsert(
['email' => 'john#example.com', 'name' => 'John'],
['votes' => '2']
);
Check this link for syntax : Laravel Doc
// Inseart code
public function create()
{
return view('admin.category.create');
}
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required'
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Saved','Success');
return redirect()->route('admin.category.index');
}
// Update code
public function edit($id)
{
$category =Category::find($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}
I'm trying to if there are records just update and if there are not records just create. Problem is:
Already has records case: It creates records when there are already have record in database.
public function store(Request $request)
{
$time = $request->input('time');
foreach ($request->input('number') as $key => $value) {
Choice::UpdateOrCreate([
'user_id' => Auth::id(),
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
You have to pass two parameters to the UpdateOrCreate the first is the attributes of searching records the second is the values in the doc of the method we have :
Create or update a record matching the attributes, and fill it with values.
So if you search the record just with the user_id you have to do it like this :
public function store(Request $request)
{
$time = $request->input('time');
foreach ($request->input('number') as $key => $value) {
Choice::UpdateOrCreate([
'user_id' => Auth::id()
],
[
'time' => $time,
'topic_id' => $key,
'question_number' => $value,
]);
}
}
use this way :
$matchThese=array('user_id' => Auth::id())
Choice::updateOrCreate($matchThese,['topic_id'=>$key,'question_number' => $value,'time' => $time]);
As per Rest Update in crud UpdateOrCreate creates a record if it doesn't finds a matching record. So, you format of Choice::UpdateOrCreate must be like this
Choice::updateOrCreate(['user_id' => Auth::id(),
'time' => $time,], [
'topic_id' => $key,
'question_number' => $value,
])
where ['user_id' => Auth::id(),
'time' => $time,] is the check for existance of a record.
Try replacing the code in the loop with this:
...
Choice::UpdateOrCreate(
['user_id' => Auth::id(), 'time' => $time],
['topic_id' => $key, 'question_number' => $value]
);
...
This will search for a record of user at specific time and create one if there is not, but if there is it will update its topic_id and question_number.
So, i'm trying to create a function that removes a post, and inserts the values into a table named "removed_post".
Now, i get the error:
No tables used
SELECT *
Line Number: 330
What causes this? I have google'd it ALOT, and tried different "answers", without any success.
Here is my code:
class Remove extends CI_Controller {
function post($id = null) {
$this->db->get_where('comments', array('id' => $id));
$query = $this->db->get();
$data = array(
'amne_id' => $query->row()->amne_id,
'user_id' => $query->row()->user_id,
'date_created' => $query->row()->date,
);
$this->db->insert('removed_post', $data);
$this->db->delete('comments', array('id' => $id));
redirect('/');
}
EDIT: And yes, the code is not optimized.
$this->db->get_where('comments', array('id' => $id));
$query = $this->db->get();
should be:
$query = $this->db->get_where('comments', array('id' => $id));
In your code the first query is run but you are not capturing the result. The second line tries to capture results for a blank query. get_where() calls get() for you so you don't have to call it explicitly.
new error
$row = $query->row();
$data = array(
'amne_id' => $row->amne_id,
'user_id' => $row->user_id,
'date_created' => $row->date,
);