get one Array from Arrays - input

in controller I have array $checked
array:4 [▼
0 => "3"
1 => "4"
2 => "5"
3 => "8"
]
from base I want get second array, like this, but cannot:
$proservices = Proservice::whereIn('service_id', $checked)->get('product_id')->toArray();
it gives me 2 arrays:
array:3 [▼
0 => array:1 [▼
"product_id" => 14
]
1 => array:1 [▼
"product_id" => 7
]
2 => array:1 [▼
"product_id" => 14
]
]
help me to get array like this:
array:2 [▼
0 => "14"
1 => "7"
]

Related

Convert Array Into String Array

array:5 [
0 => array:1 [
"location_id" => 1
]
1 => array:1 [
"location_id" => 4
]
2 => array:1 [
"location_id" => 6
]
3 => array:1 [
"location_id" => 7
]
4 => array:1 [
"location_id" => 8
]
]
convert this into ["1","4","6","7","8",]
as used this ["1","4","6","7","8",]array in different query
You can use Laravel Collection pluck method to only return property which you want from each array item, and after that flatten the result array with flatten
$data = [
[
"location_id" => 1
],
[
"location_id" => 4
],
[
"location_id" => 6
],
[
"location_id" => 7
],
[
"location_id" => 8
]
];
$result = collect($data)->pluck('location_id')->flatten();
You can use the laravel helper array flatten method: Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-flatten
// Add the helper class call in the controller header
use Illuminate\Support\Arr;
// The actual array
$array = [
0 => [
"location_id" => 1
],
1 => [
"location_id" => 4
],
2 => [
"location_id" => 6
],
3 => [
"location_id" => 7
],
4 => [
"location_id" => 8
]
];
// Flatten the array function
$result = Arr::flatten($array);
Results:
['1','4','6','7','8']
Not as clean you might want but get the job done:
$resultSet = collect($data)->map(function($item){
return $item['location_id'];
})->toArray();
$resultString = "[";
foreach($resultSet as $item){
$resultString .= "'{$item}'" . ",";
}
$resultString = rtrim($resultString, ","); // produces this: "['1','4','6','7','8']"
$resultString .= "]";
dd($resultString);
You can use the laravel helper array pluck method Read more about it from here: https://laravel.com/docs/9.x/helpers#method-array-pluck
$array = [
0 => [
"location_id" => 1
],
1 => [
"location_id" => 4
],
2 => [
"location_id" => 6
],
3 => [
"location_id" => 7
],
4 => [
"location_id" => 8
]
];
$data = \Arr::pluck($array, 'location_id'); // [1,4,6,7,8]
$result = array_map('strrev', $data);
Result
["1","4","6","7","8"]

htmlspecialchars() expects parameter 1 to be string, array given in laravel 8 with stored procedure blade file error

I am fetching data from database using stored procedure but getting below error
htmlspecialchars() expects parameter 1 to be string, array
Below is the controllers
public function index()
{
$id=2;
// $single_blog['user'] = UserRole::where('id',$id)->get();
$single_blog['user'] = DB::select("CALL FetchUserRoleWithId(".$id.")");
return view('home',$single_blog);
}
In view simple use only as
{{$user}}
If i use get() method then properly print $user data in blade file.
But using stored procedure getting below error
"htmlspecialchars() expects parameter 1 to be string, array"
Using stored procedure getting below data
array:1 [▼
"user" => array:1 [▼
0 => {#1237 ▼
+"id": 2
+"name": "SO"
+"status": "1"
+"created_by": null
}
]
]
Using get() method getting below data
array:1 [▼
"user" => Illuminate\Database\Eloquent\Collection {#1257 ▼
#items: array:1 [▼
0 => App\Models\UserRole {#1258 ▼
#fillable: array:4 [▶]
#connection: "mysql"
#table: "user_roles"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:8 [▼
"id" => 2
"name" => "SO"
"status" => "1"
"created_by" => null
"updated_by" => null
"deleted_at" => null
"created_at" => null
"updated_at" => null
]
#original: array:8 [▶]
#changes: []
#casts: array:1 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
#forceDeleting: false
}
]
#escapeWhenCastingToString: false
}
]
Anyone have idea how to display this data in blade file.

Call to a member function stripe() on null when cancelling the subscription

I am using Laravel 8 and Laravel Cashier for my subscriptions
When I tried to cancel the subscription, it returns
Call to a member function stripe() on null
when cancelling the subscription
Even the Auth::check() returns true
Here is my cancelSubscription method
public function cancelSubscription(Request $request){
$user = $request->user();
try{
// if(Auth::check()){
$user->subscription('My-Subscription-Name')->cancel();
// }
if($request->ajax()) {
return response([
'success' => true,
'data' => "Successfully subscribed"
], 200);
}
}catch (\Throwable $ex) {
Log::critical($ex);
if($request->ajax()) {
return response([
'success' => false,
'data' => "Server Error"
], 422);
}
}
}
Here is the code in api.php for the cancel subscription method
Route::post('/cancel-sub',[SubscriptionController::class, 'cancelSubscription'])->middleware('auth:api');
I've also tried this
public function cancelSubscription(Request $request){
$user = UserSubscription::where('stripe_id', $request->subId)->first(); //returns subscription id
try{
// if(Auth::check()){
$user->subscription('My-Subscription-Name')->cancel();
// }
if($request->ajax()) {
return response([
'success' => true,
'data' => "Successfully subscribed"
], 200);
}
}catch (\Throwable $ex) {
Log::critical($ex);
if($request->ajax()) {
return response([
'success' => false,
'data' => "Server Error"
], 422);
}
}
}
I've also tried
$user = $request->user();
$subscriptions = $user->subscriptions()->active()->first();
$subscriptions->cancel();
but it still doesn't work. Any answers will be appreciated.
I also did dd(auth()->user()->subscription('My-Subscription-Name')) and it returns true and here is the result
Laravel\Cashier\Subscription {#1293
#guarded: []
#with: array:1 [
0 => "items"
]
#casts: array:1 [
"quantity" => "integer"
]
#dates: array:4 [
0 => "created_at"
1 => "ends_at"
2 => "trial_ends_at"
3 => "updated_at"
]
#billingCycleAnchor: null
#connection: "mysql"
#table: "subscriptions"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:12 [
"id" => 32
"user_tbl_id" => 4697
"name" => "My-Subscription-Name"
"stripe_id" => "sub_xxx"
"stripe_status" => "active"
"stripe_price" => "price_xxx"
"quantity" => 1
"trial_ends_at" => null
"ends_at" => null
"expires_at" => "2022-10-13 20:38:54"
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#original: array:12 [
"id" => 32
"user_tbl_id" => 4697
"name" => "Choi-Nomi"
"stripe_id" => "sub_xxx"
"stripe_status" => "active"
"stripe_price" => "price_xxx"
"quantity" => 1
"trial_ends_at" => null
"ends_at" => null
"expires_at" => "2022-10-13 20:38:54"
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#changes: []
#classCastCache: []
#attributeCastCache: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [
"items" => Illuminate\Database\Eloquent\Collection {#1303
#items: array:1 [
0 => Laravel\Cashier\SubscriptionItem {#1301
#guarded: []
#casts: array:1 [
"quantity" => "integer"
]
#connection: "mysql"
#table: "subscription_items"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:9 [
"id" => 33
"subscription_id" => 32
"stripe_id" => "si_xxx"
"stripe_product" => "prod_xxx"
"stripe_price" => "price_xxx"
"quantity" => 1
"user_subscription_id" => null
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#original: array:9 [
"id" => 33
"subscription_id" => 32
"stripe_id" => "si_xxx"
"stripe_product" => "prod_xxx"
"stripe_price" => "price_xxx"
"quantity" => 1
"user_subscription_id" => null
"created_at" => "2022-09-13 20:38:54"
"updated_at" => "2022-09-13 20:38:54"
]
#changes: []
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#paymentBehavior: "allow_incomplete"
#prorationBehavior: "create_prorations"
}
]
#escapeWhenCastingToString: false
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#couponId: null
#promotionCodeId: null
#allowPromotionCodes: false
#paymentBehavior: "allow_incomplete"
#prorationBehavior: "create_prorations"
}
I did have a look at my old project and what I did was add another method on User Model, to also delete the subscription related entries on the database
public function cancelStripeSubscription( $name = 'My Subscription Name') {
$sub = $this->subscription($name);
if ( $sub ) {
DB::table('subscriptions')->where('id', $sub->id)->delete();
DB::table('subscription_items')->where('subscription_id', $sub->id)->delete();
if ( $sub->stripe_status != 'canceled' )
$sub->cancelNow();
}
}
so you can simply call auth()->user()->cancelStripeSubscription();
In you code however, you should first check if they have active subscription or subscribe to specific product by checking subscription status
something like this;
public function cancelSubscription(Request $request){
try{
if ( auth()->user()->subscribed('default') )
/*
or if ( $user->subscribedToProduct('prod_premium', 'default'))
or if ( $user->subscribedToPrice('price_basic_monthly', 'default'))
or
$sub = auth()->user()->subscription('My-Subscription-Name')
if ( $sub && $sub->stripe_status == 'canceled' )
*/
{
auth()->user()->subscription('My-Subscription-Name')->cancel();
} else {
return response([ 'error' => true, 'message' => 'You have no active subscription' ], 404);
}
.
.
}
.
.
}
Furthermore, verify if that subscripton your trying to cancel really is a subscription object and check if user is even have a subscription
public function cancelSubscription(Request $request){
return [
'request' => $request->all(),
'user' => auth()->user(),
'subscription' => auth()->user()->subscription('My-Subscription-Name'),
'subscriptions' => auth()->user()->subscriptions()
]
.
.
}

Laravel 5.3 - Missing "value" attribute in query builder

I am new to Laravel and Yajra datatable. I have developed a web application (In windows XAMPP) and everything works perfectly until I upload my project in shared hosting (UNIX) recently, the datatable unable to load the view and throwing the error message.
The error message I get is:
ErrorException in Request.php line 38:
Undefined index: value
in Request.php line 38
at HandleExceptions->handleError('8', 'Undefined index: value', '/home/posgb/public_html/boatMain/vendor/yajra/laravel-datatables-oracle/src/Request.php', '38', array()) in Request.php line 38
I have compared DD results of my query builder output in both my machine and server and found that the "value" attribute was missing from the "search" array.
My query:
$query = DB::table('item_subcat')
->leftJoin('item_customized', 'item_subcat.subcatID', '=', 'item_customized.subcatID')
->join('item_cat', 'item_subcat.itemCatID', '=', 'item_cat.itemCatID')
->select(array('item_subcat.subcatID', 'item_subcat.itemCode', 'item_subcat.itemName', 'item_cat.itemCatName', 'item_customized.customize_name', DB::raw('IF(item_subcat.is_categorize = "0", item_subcat.itemPrice, item_customized.price) AS ITEMPRICE'), 'item_subcat.is_activate', 'item_customized.itemCustomID'));
dd($query);
DD results in my pc:
#parameters: array:7 [
"draw" => "1"
"columns" => array:7 [
0 => array:5 [ …5]
1 => array:5 [ …5]
2 => array:5 [ …5]
3 => array:5 [ …5]
4 => array:5 [ …5]
5 => array:5 [ …5]
6 => array:5 [ …5]
]
"order" => array:1 [
0 => array:2 [ …2]
]
"start" => "0"
"length" => "10"
"search" => array:2 [
"value" => "" /*This is the missing value */
"regex" => "false"
]
"branch" => "ALL"
]
}
DD result in my server:
+request: ParameterBag {#41
#parameters: array:7 [
"draw" => "1"
"columns" => array:7 [
0 => array:5 [ …5]
1 => array:5 [ …5]
2 => array:5 [ …5]
3 => array:5 [ …5]
4 => array:5 [ …5]
5 => array:5 [ …5]
6 => array:5 [ …5]
]
"order" => array:1 [
0 => array:2 [ …2]
]
"start" => "0"
"length" => "10"
"search" => array:1 [
"regex" => "false"
]
"branch" => "ALL"
]
}
Please can advise me where should I look into the missing "value" in array, as it cause me unable to generate the datatable. TYVM for those spent times to look at this.
The reason was due to PHP.ini settings in my server which disallow null value in GET and POST request by default.

guzzle and last fm API

I'm using Laravel for about one month and i wanted to try the guzzle module, to get last fm user infos
I've tried this request in my controller :
$client = new \GuzzleHttp\Client(['base_uri' => 'http://ws.audioscrobbler.com/']);
//$client = new \GuzzleHttp\Client();
$response = $client->get('2.0/?method=user.getinfo&user=rj&api_key=xxxxxxxxxx&format=json');
dd($response);
but i've just got this kind of things
Response {#190 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:11 [▼
"date" => array:1 [▶]
"server" => array:1 [▼
0 => "Apache/2.2.22 (Unix)"
]
"x-web-node" => array:1 [▼
0 => "www223"
]
"access-control-allow-origin" => array:1 [▼
0 => "*"
]
"access-control-allow-methods" => array:1 [▼
0 => "POST, GET, OPTIONS"
]
"access-control-max-age" => array:1 [▼
0 => "86400"
]
"cache-control" => array:1 [▼
0 => "max-age=60"
]
"expires" => array:1 [▶]
"content-length" => array:1 [▼
0 => "642"
]
"connection" => array:1 [▶]
"content-type" => array:1 [▶]
]
-headerLines: array:11 [▶]
-protocol: "1.0"
-stream: Stream {#181 ▼
-stream: :stream {#237 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
Could someone help me with an example or something :) ?
For body's contents:
echo $response->getBody();