I am having troubles at this situation.
This is what I show in Postman
Controller
public function index(Request $request)
{
$user = Auth::guard('api');
if ($user)
{
$parameters=new UserParameters();
$parameters->id_user=Auth::guard('api')->id();
$parameters->day=$request->day;
if($parameters->save())
{
$times=$request->time;
foreach ( $times as $time)
{
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time[0];
$new_time->hour = $time[1];
$new_time->save();
}
return response()->json(['true' => false, 'message' => 'Saved!']);
}
}
else
{
return response()->json(['error' => false, 'message' => 'User not found!']);
}
}
I stuck at for loop. How can I handle this situation ?
This is what i get in database
This is because of how your key's are named. time[0].time is not valid and maybe it is reading it to time[0] only. Which is why you are only getting the hours. time[0].time = 'morning';
time[0].hour = '10:00';
- then it will not count the .time or the .hour because that is not valid. then it would only make it time[0] which then explains why you are only getting the hours.
With the changes on the postman data that I asked you to do. You can try this solution.
public function index(Request $request)
{
$user = Auth::guard('api');
if ($user)
{
$parameters=new UserParameters();
$parameters->id_user=Auth::guard('api')->id();
$parameters->day=$request->day;
if($parameters->save())
{
$data= $request->all();
foreach ( $data['times'] as $time)
{
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time[0];
$new_time->hour = $time[1];
$new_time->save();
}
return response()->json(['true' => false, 'message' => 'Saved!']);
}
}
else
{
return response()->json(['error' => false, 'message' => 'User not found!']);
}
}
Problem
I don't know how your code works, because this for ( $times as $time) is not how for works.
Here is a explanation on for
https://secure.php.net/manual/pt_BR/control-structures.for.php
Solution
The as on the for make me think your trying to use the foreach.
And here is how it works:
foreach( $times as $time) the $time is already a single record from the array
So when you do a foreach this is how it should look:
foreach ( $times as $time){
$new_time = new TimeParameter();
$new_time->id_parameter = $parameters->id;
$new_time->time = $time->time;
$new_time->hour = $time->hour;
$new_time->save();
}
Related
I have a problem, I am currently doing a search by date range of maximum 10 days and the issue is that if there are more than 10 messages or there is a total of 38 messages it takes 4 to 5 minutes to load the data, so I wanted to know if there is a way to bring it paginated directly when doing the query in Horde.
public function connect($username, $password, $hostname, $port, $ssl, $folder, $debug = 0, $cache = 0)
{
$opt = [
'username' => $username,
'password' => $password,
'hostspec' => $hostname,
'port' => $port,
'secure' => $ssl,
];
if ($debug) $opt['debug'] = Log::debug("message");
if ($cache) $opt['cache'] = array(
'backend' => new \Horde_Imap_Client_Cache_Backend_Cache(array(
'cacheob' => new Horde_Cache(new Horde_Cache_Storage_File(array(
'dir' => '/tmp/hordecache'
)))
))
);
static::$folder = 'INBOX';
try {
return static::$client = new \Horde_Imap_Client_Socket($opt);
} catch (\Horde_Imap_Client_Exception $e) {
// Any errors will cause an Exception.
dd('Error');
}
}
public function searchSince($date_string)
{
try {
$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
new Horde_Imap_Client_DateTime($date_string), Horde_Imap_Client_Search_Query::DATE_SINCE
);
$results = static::$client->search(static::$folder,$query);
} catch (\Exception $th) {
dd('Since Mail');
}
if ($results) {
static::$var = $results['match']->ids;
return true;
}
return false;
}
//I get the header data of each message (subject, date, uid, from, client name)
public function next(){
if ($var = next(static::$var)) {
static::$id = $var;
$headers = HordeImap::fetchHeaders(static::$id);
static::$clientName = $headers->getHeader('From')->getAddressList(true)->first()->__get('personal');
static::$fromEmail = $headers->getHeader('From')->getAddressList(true)->first()->__get('bare_address');
static::$subject = $headers->getHeader('subject')->__get('value');
$emailDate = $headers->getHeader('Date')->__get('value');
$unixTimestamp = strtotime($emailDate);
static::$emailDate = date('Y-m-d H:i:s',$unixTimestamp);
return true;
}
return false;
}
Controller
$mailb = new HordeImap();
$mailb->connect($userMail->client,$userMail->secret_token,$userMail->server,$userMail->port,'ssl','INDEX',1);
$msgs = $mailb->searchSince(date('d F Y', strtotime(date("Y-m-d", time()) . " -10 days")));
static::$mailbox = [];
if($msgs) while($mailb->next()){
static::$mailbox[] = [
'uid' => $mailb::$id,
'from' => $mailb::$fromEmail,
'client'=> $mailb::$clientName,
'date' => $mailb::$emailDate,
'subject'=> $mailb::$subject,
];
}
// I page the array once I have obtained all the contents.
$page = null;
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = static::$mailbox instanceof Collection ? static::$mailbox : Collection::make(static::$mailbox);
dd(new LengthAwarePaginator($items->forPage($page, 5), $items->count(), 5, null, []));
This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id
I want to save the same data with 365 records within one table. I'm new to Laravel.
I've tried with replicate() but was unsuccessful. I tried this on the Apache server and used Laravel5.7.
my controller
public function price_save(Request $request) {
$price=new Price();
$price->price=$request->price;
$price->extra_bed=$request->extra_bed;
$price->room_id=$request->room;
$id=$request->room;
$price = Price::find($id);
if(null !== $price){
$new = $price->replicate();
if(null !== $new){
$new->push();
// $price->save();
}
I am NOT sure about your code, But you can customize it as per your needs, To just get idea :
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
foreach($model->getRelations() as $relation => $items){
foreach($items as $item){
unset($item->id);
$newModel->{$relation}()->create($item->toArray());
}
}
Credits
public function price_save(Request $request, int $id)
{
if ($id > 365) {
return;
}
$price = new Price();
$price->price = $request->price;
$price->extra_bed = $request->extra_bed;
$price->room_id = $request->room;
$price->save();
$existing = Price::find($request->room);
if ($existing) {
$request = $request->replace([
'price' => $price->price,
'extra_bed' => $price->extra_bed,
'room_id' => $price->room,
]);
}
return price_save($request, $id++);
}
hi i have developed my project in Laravel 4.2 version and i have an array of record and i want to insert this data into database using built-in insert() function but i want to update those entries which are already inserted otherwise insert the record. Can anyone help me
here is my sample code
public static function followAllUsers($user_data) {
$responce = array();
$data = array();
foreach ($user_data['following_id'] as $key => $value) {
$following = UserBussinessLogic::checkAndValidateUser($value);
if ($following != true) {
$responce = Utility::Responce('invalid_user', FALSE, $value);
break;
} else {
if (FriendBussinessLogic::isAlreadyFollowed($user_data['id'], $value)) {
continue;
}
$data[] = array('follower_id' => $user_data['id'], 'following_id' => $value, 'created_at' => date('Y-m-d H:i:s'));
$followData['notifyAbleUsers'][] = $value;
}
}
if ($following) {
if (!empty($data)) {
if (Friend::insert($data)) {
$followData['created_at'] = date('Y-m-d H:i:s');
$followData['follower_id'] = $user_data['id'];
$responce = Utility::Responce('friend_followed', TRUE, $followData);
} else {
$responce = Utility::Responce('general_error', FALSE);
}
} else {
$responce = Utility::Responce('already_followed', TRUE);
}
}
return $responce;
}
Thank you
A little lesser known function that is also available in Laravel 4.2 is:
updateOrCreate
Here's an example on how to use it:
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
Am trying to encode an array to json for use with jquery.
This is the function from my model
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->group_by('pheed_id')
->order_by('datetime','desc')
->limit(30);
$rows = $q->get();
foreach($rows->result_array() as $row) {
$data['user_id'] = $row['user_id'];
$data['pheed_id'] = $row['pheed_id'];
$data['pheed'] = $row['pheed'];
$data['comments'] = $row['comments'];
$data['datetime'] = timespan($row['datetime'],$time);
}
return $data;
}
And this is from my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
return false;
}
}
It returns only 1 row from the database when I run the code in the browser.
Please help me out
You are overwriting data in every iteration !!
Use something like
$data[] = array(
'user_id' => $row['user_id'];
'pheed_id' => $row['pheed_id'];
'pheed' => $row['pheed'];
'comments' => $row['comments'];
'datetime' => timespan($row['datetime'],$time);
) ;
This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array