I want to group my posts by day, sort by latest, and include pagination for a timeline that will also contain infinite scroll for a vue spa on the frontend:
RecordController
public function userFeed($userId)
{
$client = User::where('hashed_id', $userId)->first();
$records = Record::where('user_id', $client->id)->latest()->paginate(10);
return RecordResource::collection($records);
}
RecordResource
class RecordResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->hashed_id,
'owner' => new UserResource($this->owner),
'title' => $this->title,
'created_at' => $this->created_at->format('M d Y'),
'comments' => $this->decryptedComments()
];
}
}
I'd like the API laid out in a way where it would be easy to loop through with v-for:
[
'Sunday' => 5,
'Monday' => 45,
'Tuesday' => 452,
...
]
<div v-for="(record, index) in records" v-bind:key="index" class="mb-10">
<div class="card>
<h1>{{record.title}}</h1>
</div>
</div>
if you want a group by then use if before pagination otherwise, it's not working
$records = Record::where('user_id', $client->id)
->groupBy(\DB::raw('DATE(created_at) = CURDATE()'))
->latest()->paginate()
Related
CakePHP Version 3.5.5
My end goal is to provide the user the functionality to change the amount of results displayed via a select list on the index view. Also I need the initial page load to be sorted by area_name asc.
// WHAT I'VE DONE
I changed where I was stipulated the limit parameter which can be seen below.
// AREAS CONTROLLER
public $paginate = [
'sortWhitelist' => [
'Areas.area_name', 'Users.first_name', 'Users.last_name'
]
//'limit' => 1, // REMOVED FROM HERE
//'order' => [ // REMOVED FROM HERE
//'Areas.area_name' => 'asc'
//]
];
public function index()
{
$query = $this->Areas->find('all')
->contain([
'Users'
])
->where(['Areas.status' => 1]);
$limit = 1;
$this->paginate = [
'order' => ['Areas.area_name' => 'asc'], // ADDED HERE
'limit' => $limit // ADDED HERE
];
$this->set('areas', $this->paginate($query));
}
And I declare the pagination sort links like:
// AREAS INDEX VIEW
<?= $this->Paginator->sort('Areas.area_name', __('Area Name')) ?>
<?= $this->Paginator->sort('Users.first_name', __('First Name')) ?>
<?= $this->Paginator->sort('Users.last_name', __('Last Name')) ?>
// RESULT
The above code works on all index methods within the application that don't use contain but when I implemented this solution here everything worked except I cannot sort on the associated data - IE: Users first and last name?
=========================================================================
WHAT I'VE TRIED
// Attempt 1
I added an initialize method above the public $paginate class like:
public function initialize()
{
$limit = 1;
}
public $paginate = [
'sortWhitelist' => [
'Areas.area_name', 'Users.first_name', 'Users.last_name'
]
'limit' => $limit,
'order' => [
'Areas.area_name' => 'asc'
]
];
public function index()
{
$query = $this->Areas->find('all')
->contain([
'Users'
])
->where(['Areas.status' => 1]);
$this->set('areas', $this->paginate($query));
}
And the view I left the same.
// Result for Attempt 1
syntax error, unexpected ''limit'' (T_CONSTANT_ENCAPSED_STRING), expecting ']' on line 36 which is 'limit' => $limit,
=========================================================================
// Attempt 2
I tried to add the limit parameter and order array to the query like:
public function index()
{
$limit = 1;
$query = $this->Areas->find('all')
->contain([
'Users'
])
->where(['Areas.status' => 1])
->order(['Areas.area_name' => 'asc'])
->limit($limit);
$this->set('areas', $this->paginate($query));
}
// Result for Attempt 2
The result set was not ordered by the area_name and not limited to 1 result.
=========================================================================
// Attempt 3
I then changed the query and tried the following just to see if I could get a dynamic limit working:
$limit = 1;
$query = $this->Areas->find('all')
->contain('Users', function ($q) {
return $q
//->order('Areas.area_name' => 'asc'),
->limit($limit);
})
->where(['Areas.status' => 1]);
$this->set('areas', $this->paginate($query));
// Result for Attempt 3
The result set was not limited to 1 result.
=========================================================================
ADDITIONAL INFORMATION
// USERS TABLE
$this->hasOne('Areas', [
'foreignKey' => 'user_id'
]);
// AREAS TABLE
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
I searched through the following cookbook sections (Pagination, Query Builder, Retrieving Data & Result Sets and Associations - Linking Tables Together) but I can't find a way to get this working so any help would be much appreciated.
Many thanks. Z.
You are overwriting the $paginate property in your index() method, so your settings including the whitelist are being lost.
Set the keys directly instead:
$this->paginate['order'] = ['Areas.area_name' => 'asc'];
$this->paginate['limit'] = $limit;
in Database i have a table of product and components
and i have a table for many to many relation which is component_product
it have an attributes of (product_id,component_id,quantity)
in model product
class Product extends Model
{
protected $fillable = [
'name','price','user_id','is_avilable','description'
];
public function components()
{
return $this->belongsToMany('App\Component')
->withPivot('quantity');
}
}
in view
{!! Form::select('component_id[]',$components,null !!}
{!! Form::select('component_id[]',$components,null !!}
{!! Form::number('quantity[]',null ]) !!}
{!! Form::number('quantity[]',null ]) !!}
in controller
public function store(Request $request)
{
$product= Product::create( $request->all() );
$product->components()->sync($request->component_id => ['quantity'=> $request->quantity ] );
}
It gives me an error of Illegal offset type
notice : if die dump $request->quantity or $request->component_id it will get the array correctly
Sync example in laravel docs (https://laravel.com/docs/5.5/eloquent-relationships)
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
Try changing , with =>
So in your case:
$product->components()->sync([$request->component_id => ['quantity'=> $request->quantity]]);
this is how i solve my own problem
in Laravel documentation
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
so to match this
$manyToMany = array();
for ( $i=0 ; $i< count($request->component_id); $i++ )
{
$manyToMany[ $request->component_id[$i] ] = ['quantity' =>$request->quantity[$i] ];
}
$product->components()->sync($manyToMany);
is their is a better solution
i have problem while displaying json data in laravel blade, i request data using guzzel and this is my code:
public function index(){
$client = new Client();
$schedules = $client->get('45.112.125.25:5500/md_data/schedules/', [
'query' => [
'vCategory' => '129',
'vStartDate' => '2017-07-01',
'vEndDate' => '2017-09-31',
'vReadKey' => 850601165,
'vRows' => 10,
'vOffset' => 0
]
]);
// return $schedules->getBody();
return view('trainingList')->with('schedules', $schedules->getBody());
}
this result :
[{"f_training_schedule_id":324,"f_training_category_id":129,"f_training_category":"Workshop Business","f_city_id":216,"f_city_name":"Kota Jakarta Selatan","f_training_schedule_startdate":"2017-08-11T17:00:00.000Z","f_training_schedule_enddate":"2017-08-12T17:00:00.000Z","f_training_schedule_batch":1,"f_training_schedule_trainer":58,"f_training_schedule_address":"<!--StartFragment-->JL TB Simatupang, Cilandak, RT.3/RW.3, Cilandak Tim., Ps. Minggu<!--EndFragment-->\r\n\r\n<br>"}]
how to get specific data from the above results.
for example I want to get value from f_training_schedule_id
You need json_decode():
return view('trainingList')->with('schedules', json_decode($schedules->getBody(), true));
In your blade template
$schedules[0]['f_training_schedule_id'];
Foreach:
#foreach ($schedules as $schedule)
<p>{{ $schedule['f_training_schedule_id'] }}</p>
#endforeach
I am sending multiple arrays via AJAX to my controller and I'm having trouble with validation.
I have 2 text inputs. Now, the issue is that at times both these inputs are present, but at other times only one might be present.
<input type="text" name="typeDetails[games]" class="form-control input-global"/>
<input type="text" name="typeDetails[art]" class="form-control input-global"/>
My JS is like this.
var data = { 'typeDetails[games]' : [], 'typeDetails[art]' : [] };
$("input[name='typeDetails[games]']").each(function() {
data['typeDetails[games]'].push($(this).val());
});
$("input[name='typeDetails[art]']").each(function() {
data['typeDetails[art]'].push($(this).val());
});
In my controller, I want to (1) make sure that there's a validation of required and (2) if the "games" array is present, perform a particular action and if the "art" array is present, perform a different action.
$typeDetails = Input::get('typeDetails');
if ($request->has('typeDetails.games'))
{
return 'games';
}
if ($request->has('typeDetails.art'))
{
return 'art';
}
What happens here is that in my console it properly returns 'games', but even if the "art" array has values and is sent with the request, it doesn't return 'art'. I must be missing a fundamental understanding with php here.
Thanks!
ANSWER
Here's how I got it to work.
$typeDetails = Input::get('typeDetails');
$this->validate($request, [
'typeDetails.*.*' => 'required|max:50'
],[
'required' => 'You must type in some keywords to continue.',
'max' => 'Your input must be less than 50 characters.'
]);
if ($request->has('typeDetails.games'))
{
$gameInfo = Input::get('typeDetails.games');
foreach ($gameInfo as $key => $value)
{
DB::table('user_type')->insert([
'user_id' => Auth::user()->id,
'type_id' => '1',
'user_type_details' => $value,
'created_at' => Carbon::now()
]);
}
}
if ($request->has('typeDetails.art'))
{
$artInfo = Input::get('typeDetails.art');
foreach ($artInfo as $key => $value)
{
DB::table('user_type')->insert([
'user_id' => Auth::user()->id,
'type_id' => '2',
'user_type_details' => $value,
'created_at' => Carbon::now()
]);
}
}
Can anyone help on editable column in gridview.I am using Yii2 and stuck with it.
I can't save data in my model.I can post from gridview column.
In my grid view:
$gridColumns= [
'patient_no',
'category_name',
'sdv_text',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'sdv_status',
'pageSummary' => true,
'editableOptions'=> [
'header' => 'profile',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=> $StatusList,
]
],
// 'date_sdv_performed',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'date_sdv_performed',
'editableOptions' => [
'header' => 'Date Sdv Performed',
'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
'format'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
'widgetClass'=> 'kartik\datecontrol\DateControl',
],
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'comments',
'hAlign' => 'top',
'vAlign' => 'middle',
'width'=>'100px',
'headerOptions' => ['class' => 'kv-sticky-column'],
'contentOptions' => ['class' => 'kv-sticky-column'],
'pageSummary' => true,
],
];
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>"{items}\n{pager}",
'pjax'=>true,
'toolbar' => [
'{export}',
'{toggleData}'
],
'responsive'=>true,
'hover'=>true,
'columns' => $gridColumns
]);
In my controller action:
public function actionMonitoring($site_name)
{
$this->layout = 'sdv-carolina-main';
$Countries = new Countries;
$model = new Flagging;
$searchModel = new FlaggingSearch();
$dataProvider = $searchModel->monitoringsearch($site_name);
$allocatedsites = new AllocatedSites;
if (Yii::$app->request->post('hasEditable'))
{
$model = $this->findModel($model['flagging_id']);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['Flagging']);
$post['Flagging'] = $posted;
if ($model->load($post)) {
$model->save();
$output = '';
if (isset($posted['sdv_status']))
{
$output = $model->sdv_status;
}
$out = Json::encode(['output'=>$output, 'message'=>'']);
}
echo $out;
return;
}
return $this->render('monitoring',
[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'Countries' => $Countries,
'model'=>$model,
'allocatedsites' => $allocatedsites,
]);
}
The problem is I can't update my model because of I can't get the id.
I just need the id to update specific row.How can I get the id while using editable column?
Thanks in advance.
Actually the solution is easy. I just need the id of that specific row to update that.And in my ajax post I got something like this:
Flagging[0][status] NO
_csrf TlhyUm5kajAoNxgVNy0/ZCoyHApZUlNUFh0rB1gRPGoAFSIdGSAifQ==
editableIndex 0
editableKey 13
hasEditable 1
and found the editableKey is the id of that specific row!
Now in my controller I write down this code given below:
$_id=$_POST['editableKey'];
$model = $this->findModel($_id);
Here $_id is the posted editableKey value which is the id of the specific row.
and with the id I use it to get the specific model and just update data based on that id.