so i have this kind of class from my user controller
public function index()
{
$table_data = User::with('CU','pus')->select('id','id_cu','id_pus','name','username','gambar','status','created_at')->filterPaginateOrder();
return response()
->json([
'model' => $table_data
]);
}
it is using trait called filterPaginateOrder and the end result that i receive are:
{
"model": {
"current_page": 1,
"data": [
{
"id": 8,
"id_cu": 0,
"id_pus": 1,
"name": "test1",
"username": "test17",
"gambar": "",
"status": 1,
"created_at": "2018-02-27 06:37:10",
"c_u": null,
"pus": {
"id": 1,
"name": "Puskopdit BKCU Kalimantan"
}
},
{
"id": 1,
"id_cu": 0,
"id_pus": 1,
"name": "tony",
"username": "t0n1zz",
"gambar": null,
"status": 1,
"created_at": "2017-01-01 11:11:11",
"c_u": null,
"pus": {
"id": 1,
"name": "Puskopdit BKCU Kalimantan"
}
}
],
"from": 1,
"last_page": 1,
"next_page_url": null,
"path": "https://bkcuvue.dev/api/v1/user",
"per_page": "2",
"prev_page_url": null,
"to": 2,
"total": 2
}
}
so what if i want to add some data into it? inside data array for each array i want to add "role":"master" how do i do that?
i tried $table_data->push('role','master') and $table_data->put('role','master') from reading about collection (those query in laravel return collection right?) but none of those code working...
There are two ways to go about it.
Add it via a foreach
$table_data = User::with('CU','pus')->select('id','id_cu','id_pus','name','username','gambar','status','created_at')->filterPaginateOrder();
foreach($table_data->data as $data) {
$data->role = 'master';
}
Or add it into the SELECT:
$table_data = User::with('CU','pus')->select('id','id_cu','id_pus','name','username','gambar','status','created_at', DB::raw('"master" as role'))->filterPaginateOrder();
Or you can override collection data of paginator object.
$table_data = User::with('CU','pus')->select('id','id_cu','id_pus','name','username','gambar','status','created_at')->filterPaginateOrder();
$table_data->getCollection()->each(function($user) {
$user->role = 'master';
});
return response()->json([
'model' => $table_data
]);
Related
I have the following function inside the UsersApiController class :-
public function getKhatmas()
{
$user = Auth::user();
$khatmas = $user->khatmas;
return response()->json($khatmas);
}
The above code give the following response :-
[
{
"id": 3,
"hash": "5ec72b4913d1a",
"type": 2,
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
},
{
"id": 4,
"hash": "5ec72b7005126",
"type": 2,
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
},
]
Relationship function in User Model file :-
public function khatmas()
{
return $this->hasMany('App\Khatma');
}
App\Khatma file content :-
public function type()
{
return $this->belongsTo('App\KhatmaType');
}
In above json response , ("type": 2) is the foreign key of App\KhatmaType Model .
I want instead of json response with the foreign key of KhatmaType Model, i want it to return the column "title" from App\KhatmaType to be like this :-
{
"id": 3,
"hash": "5ec72b4913d1a",
"type": "this is title from App\KhatmaType Model",
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
}
`I tried with the following :-
$khatmas = $user->khatmas->with('type');
But it return error : Method Illuminate\Database\Eloquent\Collection::with does not exist
Fixed by using the following query builder:-
public function getKhatmas()
{
$user = Auth::user();
$khatmas = Auth::user()->khatmas()
->select('hash','type_text','status','expiry_date','type_id')
->with('type')->get();
return response()->json($khatmas);
}
I have categories with id, parent_id, slug , pivot table category_language which columns are id,category_id,language_id,value
As you can see I can translate parent category, but can't send desired $lang_id to children translations, so each children having all translations
here is what I get:
{
"id": 1,
"parent_id": 0,
"slug": "personal-computers",
"created_at": "2019-12-27 15:05:31",
"updated_at": "2019-12-27 15:05:31",
"children": [
{
"id": 3,
"parent_id": 1,
"slug": "accessories-for-pc",
"created_at": "2019-12-27 15:05:32",
"updated_at": "2019-12-27 15:05:32",
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 3,
"language_id": 1,
"value": "Acc for PC",
"id": 7
}
},
{
"id": 2,
"code": "ru",
"name": "Русский",
"pivot": {
"category_id": 3,
"language_id": 2,
"value": "Аксессуары для ноутбуков и ПК",
"id": 8
}
},
{
"id": 3,
"code": "ro",
"name": "Romana",
"pivot": {
"category_id": 3,
"language_id": 3,
"value": "aksessuari-dlya-noutbukov-i-pk-ro",
"id": 9
}
}
]
}
],
"translations": [
{
"id": 1,
"code": "en",
"name": "English",
"pivot": {
"category_id": 1,
"language_id": 1,
"value": "PC",
"id": 1
}
}
]
}
Controller:
return Category::with('children')
->with(array('translations'=>function($query) use ($lang_id){
$query->where('language_id',$lang_id);
}))
->where('parent_id',0)->first();
Model
class Category extends Model
{ ..
public function translations()
{
return $this->belongsToMany('App\Models\Translation','category_language', 'category_id' ,'language_id' )->withPivot('value','id');
}
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations');
}
}
you can add condition in children method
public function children()
{
return $this->hasMany( 'App\Models\Category' , 'parent_id' , 'id' )->with('translations')->where('language_id', 1);
}
Dry7 answer was close to the one I've implemented later, so I upvoted him.
Finally in model I've added: ...->where('language_id',helper_SetCorrectLangIdForQuery());
and function helper_SetCorrectLangIdForQuery is using global helper of Laravel request()->lang . If lang=enz, than it takes default language from another helper.
I Have one Table That is tbl_service
table_service has relation with 4 other table as below
tbl_service_review
tbl_service_images
tbl_service_packages
tbl_service_step
tbl_user
I Have Joined This Four Table With Tbl_service Model Relationship. Now, I want To Subjoin table_user into tbl_service_review.......basically i want reviewer profile_pic And His Name from database......i have already joined tbl_user for who added service......
please help me with this......
Thank You In Advance.
function get_service_detail_by_id(Request $request) {
$rule = [
'service_id' => 'required',
];
$validate = Validator::make(request()->all(), $rule);
if ($validate->fails()) {
return response()->json(['data' => ['errors' => $validate->errors()->all()], 'message' => 'validation fail', 'status' => '0'], 406);
}
$userId = Auth::id();
$service_id = $request->input('service_id');
$package = Tbl_service::select(array('tbl_service.*',
DB::raw("IFNULL((select IFNULL(avg(rate),0) from tbl_rating where service_id = tbl_service.service_id group by service_id),0) as avg_rating"),
DB::raw("IFNULL((select COALESCE(count(rate),0) from tbl_rating where service_id = tbl_service.service_id group by service_id),0) as total_rating"),
DB::raw("IFNULL((select COALESCE(count(like_to),0) from tbl_service_favorite where like_to = tbl_service.service_id group by service_id),0) as total_like"),
DB::raw("IFNULL((select CASE WHEN id THEN 1 END from tbl_service_favorite where like_to = tbl_service.service_id and like_by = $userId group by tbl_service.service_id),0) as is_like_by_me"),
))
->with('Images', 'Packages', 'User_data', 'Steps')
->where('service_id', $service_id)
->get();
return response()->json(['data' => $package, 'message' => 'Get List Service Detail Successfully', 'status' => 1], 200);
}
Table_service Model
public $timestamps = false;
protected $table = 'tbl_service';
public function Images() {
return $this->hasMany('App\Models\Tbl_service_image', 'service_id', 'service_id');
}
public function Packages() {
return $this->hasMany('App\Models\Tbl_service_package', 'service_id', 'service_id');
}
public function User_data() {
return $this->hasMany('App\User', 'id', 'seller_id');
}
public function Steps() {
return $this->hasMany('App\Models\Tbl_service_step', 'service_id', 'service_id');
}
public function Review() {
return $this->hasMany('App\Models\Tbl_rating', 'service_id', 'service_id');
}
}
My Current Response is
"data": [
{
"service_id": 2,
"category_id": 2,
"seller_id": 1,
"service_title": "text",
"service_package": 3,
"created_at": "2019-08-06 09:20:45",
"avg_rating": "5.0000",
"total_rating": 2,
"total_like": 0,
"is_like_by_me": 0,
"Review": [
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
},
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
}
],
"user_data": [
{
"id": 1,
"role": 0,
"thirdparty_id": null,
"login_by": 0,
"name": "Test User",
"email": "test_user#gmail.com",
"country": "India",
"languages": "English",
"profile_pic": "https://images.unsplash.com/photo-1497316730643-415fac54a2af?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"is_online": 0,
"last_seen": null,
"description": "User Details",
"password": "$2y$10$qf1ohDCSb0x7HrFDvF6cWe.B1V41r4gjuAhMm0DQFyhM1fy7ieKR2",
"temp_pass": null,
"is_active": 1,
"is_blocked": 0,
"user_lat": "21.12345",
"user_long": "72.12345",
"created_at": "2019-08-02 08:49:48"
}
],
}
],
"message": "Get List Service Detail Successfully",
"status": 1
My Expected Response Is
"data": [
{
"service_id": 2,
"category_id": 2,
"seller_id": 1,
"service_title": "Text",
"service_package": 3,
"created_at": "2019-08-06 09:20:45",
"avg_rating": "5.0000",
"total_rating": 2,
"total_like": 0,
"is_like_by_me": 0,
"Review": [
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
"name": "trst",
"profile_pic": "https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg"
},
{
"rating_by": 2,
"rate": 5,
"rating_text": "Good",
"created_at": "2019-08-06 10:09:33",
"name": "trst",
"profile_pic": "https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg"
}
],
"user_data": [
{
"id": 1,
"role": 0,
"thirdparty_id": null,
"login_by": 0,
"name": "Test User",
"email": "test_user#gmail.com",
"country": "India",
"languages": "English",
"profile_pic": "https://images.unsplash.com/photo-1497316730643-415fac54a2af?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"is_online": 0,
"last_seen": null,
"description": "User Details",
"password": "$2y$10$qf1ohDCSb0x7HrFDvF6cWe.B1V41r4gjuAhMm0DQFyhM1fy7ieKR2",
"temp_pass": null,
"is_active": 1,
"is_blocked": 0,
"user_lat": "21.12345",
"user_long": "72.12345",
"created_at": "2019-08-02 08:49:48"
}
],
}
],
"message": "Get List Service Detail Successfully",
"status": 1
What your are looking forward to is merging relationship
Here is the link
Just merge Review relationship merge useredata->pluck('profile_pic') and review object
I want to create story for my ios app, I am trying to get useful json response for it. I want to show same user stories in a group inside of that user`s array.
Current JSON RESULT;
{
"current_page": 1,
"data": [
{
"id": 3,
"name": "Muhammed Ali Yüce",
"username": "ali",
"avatar": "1544128196.png",
"stories": {
"id": 3,
"user_id": 3,
"image": "1550228567.jpg",
"created_at": "2019-02-15 11:02:47",
"updated_at": "2019-02-15 11:02:47"
}
},
{
"id": 2,
"name": "Ömer Faruk YÜCE",
"username": "omer",
"avatar": "1544128227.png",
"stories": {
"id": 2,
"user_id": 2,
"image": "1550228407.jpg",
"created_at": "2019-02-15 11:00:08",
"updated_at": "2019-02-15 11:00:08"
}
},
{
"id": 2,
"name": "Ömer Faruk YÜCE",
"username": "omer",
"avatar": "1544128227.png",
"stories": {
"id": 1,
"user_id": 2,
"image": "1550072626.jpg",
"created_at": "2019-02-13 15:43:47",
"updated_at": "2019-02-13 15:43:47"
}
}
],
"first_page_url": "/?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "/?page=1",
"next_page_url": null,
"path": "/",
"per_page": 10,
"prev_page_url": null,
"to": 3,
"total": 3
}
I did tried groupBy func for it but it was not what I excepted.
I want to get result like this;
{
"id": 3,
"name": "Muhammed Ali Yüce",
"username": "ali",
"avatar": "1544128196.png",
"stories": [
{
"id": 2,
"user_id": 3,
"image": "1550228567.jpg",
"created_at": "2019-02-15 11:02:47",
"updated_at": "2019-02-15 11:02:47"
},
{
"id": 3,
"user_id": 3,
"image": "1550228567.jpg",
"created_at": "2019-02-15 11:02:47",
"updated_at": "2019-02-15 11:02:47"
}
]
StoryController.php
<?php
namespace App\Http\Controllers;
use App\Story;
use App\User;
use Illuminate\Http\Request;
use Image;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
class StoryController extends Controller
{
public function index(Request $request){
$userId = $request->id;
$followsArr = [$userId];
$follows = DB::table('follows')->whereNotIn('ismuted', [1])->where('follower', $userId)->get();
foreach ($follows as $follow) {
$friend = $follow->following;
$followsArr[] = $friend;
}
$itemCollection = collect($followsArr);
$stories = [];
Story::whereIn('user_id', $itemCollection)
->orderBy('created_at', 'DESC')
->get()->each(function ($story) use (&$stories){
$user = User::where('id', $story->user_id)->first();
$stories[] =
['id' => $user->id]
+ ['name' => $user->name]
+ ['username' => $user->username]
+ ['avatar' => $user->avatar]
+ ['stories' => $story->toArray()];
});
// Get current page form url e.x. &page=1
$currentPage = LengthAwarePaginator::resolveCurrentPage();
// Create a new Laravel collection from the array data
$itemCollection = collect($stories);
// Define how many items we want to be visible in each page
$perPage = 10;
// Slice the collection to get the items to display in current page
$currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
// Create our paginator and pass it to the view
$paginatedItems= new LengthAwarePaginator($currentPageItems , count($itemCollection), $perPage);
return response()->json($paginatedItems);
}
I hope you will understand what I mean, Thanks in advance :)
Assume you have User.php and Story.php Models
In User.php
public function stories()
{
return $this->hasMany(Story::class);
}
You can load story along with user. something like that
$user = User::where('id', $story->user_id)->with('stories')->first(); //Eager Load
or
$user = User::where('id', $story->user_id)->first();
$user->load('stories'); //Lazy Eager Load
Please read more about Laravel Eloquent: Relationships
I have this data in method of controller as you see I deleted some keys in method:
$foods = Food::get()->map(function($value){
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
return HttpHelpers::sendJsonData($foods, 200);
and the api response returns this:
{
"success": true,
"data": [
{
"id": 1,
"title": "food1",
"default_price": 2353465456,
"main_meal": 1,
"labels": [
{
"id": 1,
"title": "type1",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 1,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
},
{
"id": 2,
"title": "food2",
"default_price": 1000,
"main_meal": 0,
"labels": [
{
"id": 1,
"title": "type2",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 2,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
}
]
}
now my problem is that I do not want to return some keys, like labalable_id and labelable_type in pivot and created_at in labels, please offer me the best way
You can use the makeHidden method for hiding data to JSON. Haven't tried this code but, i think it should work.
https://laravel.com/docs/5.6/eloquent-serialization#hiding-attributes-from-json
$foods = Food::get()->map(function($value){
foreach($value->labels as $label){
$label = $label->makeHidden(['created_at']);
$label->pivot = $label->pivot->makeHidden(['labelable_id', 'labelable_type']);
}
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
If the data response is coming through the stored procedure then in that case you need to store the Pivot table data in a temporary table and select the required keys that you require and display it through API in json.