Laravel guzzel result implement to blade laravel - laravel

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

Related

Pass data returned by eloquent Model::find() to DomPDF data array

The problem to solve:
In the front end, the user selects several posts from a list and press a button to export this selection of posts to pdf (send the ids of these posts in the axios request).
On the server side, the posts corresponding to these ids are retrieved with $posts = Post::find($payload);
It follows the whole process of creating the pdf with DomPDF and blade.
The problem to solve, specifically, is sending the $posts to the blade file.
Front End Vue/Quasar
posts: [
0 : {id: 1, name: 'Post one'}
1 : {id: 2, name: 'Post two'}
]
let payload = posts.map((obj) => obj.id);
this.$axios
.post(`pdf_posts`, payload)
.then((response) => {
window.open(response.request.responseURL);
})
.catch((error) => {});
pdf_posts.blade.php
{{-- Comment: Just to check; returns [] --}}
<div> {{ $posts'] }}</div>
#foreach ($posts as $post)
<div> {{ $post['name'] }}</div>
#endforeach
Laravel controller
public function generatePostsPdf(Request $request)
{
$payload = $request->all();
$posts = Post::find($payload);
/*
return response()->json(["posts" => $posts]);
//return posts
posts: [
0 : {id: 1, name: 'Post one'}
1 : {id: 2, name: 'Post two'}
]
*/
$data = [
'posts' => $posts, // in pdf_posts.blade.php file returns []
];
$pdf = Pdf::loadView('pdf_posts', $data);
return $pdf->stream("pdf_posts.pdf");
}
In this specific case, how to correctly pass $posts to $data = [ 'posts' => $posts ];
EDITED
The problem may be in the output format of the data returned in $payload and passed to the find() method.
If $payload = $request->all(); is replaced with $payload = [1, 2] works fine;

Laravel group by day and paginate?

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()

Laravel Illegal offset type on many to many with extra column

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

Laravel putting the return of a trait array into the controller

I'm currently struggling with how to return a variables from a trait and it should be returned in the array to be used in the controller:
Trait:
public function getAllData($search)
{
if ($search->search == null) {
$search->search = '#technology';
}
$cb = new Codebird();
$cb->setConsumerKey(env('TwitterKey'), env('TwitterSecret'));
$cb->setToken(env('AccessToken'), env('AccessTokenSecret'));
//https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
//https://dev.twitter.com/docs/api/1.1/get/search/tweets
$params = [
'q' => $search->search,
'lang' => 'en',
'count' => '5',
];
$reply = (array)$cb->search_tweets($params);
$data = (array)$reply['statuses'];
$s = count($reply['statuses']);
return [
'data' => $data,
's' => $s,
];
Controller:
public function TwitterData(Request $search) {
$data = $this->getAllData($search);
return view('front.search', compact('data'));
}
It currently gives me an error saying about using the object however I can't access the 'data' in the array
Error:
Trying to get property of non-object (View: C:\xampp\htdocs\TwitterProject\resources\views\front\search.blade.php)
You are returning an array on your getAllData method, but you are probably trying to access it as an object on your View:
WRONG:
{!! $data->data !!}
RIGHT:
{!! $data['data'] !!}

Laravel parsing Input from a multiple select box not working

This is my pubf in my Controller which handles the request:
public function addPermissionsToRoleHandler($rid, Request $request)
{
$role = Role::find($rid);
dd($request->permissions);
foreach($request->permissions as $perm)
{
$permission = Permission::find($perm->id);
$role->attachPermission($permission);
}
return redirect()->route('showSpecificRole', $rid);
}
This is how I defined my multiple select-box:
{!! Form::select('permissions[]', $permissions, null, array('class' => 'selectpicker show-tick', 'data-live-search' => 'true', 'id' => 'permission_select', 'multiple' => true)) !!}
Why is my dd() returning null? $request->permission is empty. dd($request) only has token_.
I don't have the rep to comment so am posting as an answer. I am not sure, but I think it may be because the Request needs to be the first argument ?

Resources