I'm trying to save an array for checkout but when i print session it gives null
namespace App\Http\Livewire;
use App\Orders;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Cart;
use Carbon\Carbon;
public function setAmountForCheckout()
{
if(session()->has('coupon'))
{
session()->put('checkout',[
'discount'=>$this->discount,
'subtotal'=>$this->subtotalAfterDiscount,
'total'=>$this->totalAfterDiscount,
]);
}
else
{
session()->put('checkout',[
'discount'=>0,
'tax'=>Cart::instance('cart')->tax(),
'subtotal'=>Cart::instance('cart')->subtotal(),
'total'=>Cart::instance('cart')->total(),
]);
session()->save();
}
}
public function placeOrder(Request $request)
{
dd(session()->get('checkout'));
$this->validate([
'first_name' => 'required|min:4|string',
'Phone_number' => 'required|digits:11'
]);
$order=new Orders();
$order->user_id=Auth::id();
$order->cust_name=$this->first_name;
$order->phone=$this->Phone_number;
$order->subtotal=session()->get('checkout')['subtotal'];
$order->discount=session()->get('checkout')['discount'];
$order->total=session()->get('checkout')['total'];
$order->status='ordered';
$order->is_shipping=$this->haveShipping ? 1:0;
foreach(Cart::instance('cart')->content() as $items)
{
$orderItem= new OrderItems();
$orderItem->product_id=$items->id;
$orderItem->price=$item->price;
$orderItem->order_id=$order->id;
$orderItem->quantity=$item->qty;
$orderItem->save();
}
if($this->haveShipping)
{
$this->validate([
'Address'=>'required|min:4',
'shipping_fee'=>'required|numeric'
]);
$order->address=$this->Address;
$order->delivery=$this->shipping_fee;
}
$order->save();
Cart::instance('cart')->destroy();
session()->forget('checkout');
}
when i remove dd it gives me the error "Trying to access array offset on value of type null"
I'm trying to find what's wrong with the session.
also i have checked the cart if it works or not but i found that it works well and delivers data.
Remove
session()->save();
This is not needed as per https://laravel.com/docs/8.x/session#storing-data
Related
In RatingController:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\RatingResource;
use App\Models\Rating\Rating;
class RatingController extends Controller
{
public function getRatingsByCategory($id)
{
$ratings = cache()->rememberForever('test', function () use ($id) {
return new RatingResource(Rating::findOrFail($id));
});
return response()->json([
'data' => $ratings
]);
}
}
in RatingResource class
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;
class RatingResource extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->rating_id,
'is_active' => $this->is_active,
'created_at' => '2020',
];
}
}
when i send request to this controller, i get this result
{
"data": {
"id": 3,
"is_active": 1,
"created_at": "2020"
}
}
but when i change each of column in RatingResource like created_at, the result changes.
indeed laravel does not cache final result, it cache the object of my request and when i return that object,it start to convert my object to resource format.
how can i cache the result of ApiResource till i delete this cache key.
You could cache the whole response, this way you would have to add the id to the cache key though, in order to differentiate between the different rating ids.
Something like this:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\RatingResource;
use App\Models\Rating\Rating;
use Illuminate\Support\Facades\Cache;
class RatingController extends Controller
{
public function getRatingsByCategory($id)
{
return Cache::rememberForever("test:{$id}", function () use ($id) {
return RatingResource(Rating::findOrFail($id));
});
}
}
I am trying to find if it possible to use the beforeAction in the controller to access the injected parameter.
For example, every action in the controller accepts type parameter, which I need to sanitize:
public function actionGetCustomPaymentsChunk($type) {
$type = TextUtil::sanitizeString($type);
// Get filter data
$filter = FilterHelper::getFilterData();
// Initialize components
$totalCostPayableComponent = new TotalCostPayableComponent($filter);
// Get chunk data
$data = $totalCostPayableComponent->getCustomPaymentChunk($type);
// Return content to client side
$this->renderPartial('/partials/_payable_cost_chunk', array(
'data' => $data,
'route' => 'totalCostPayable/getCustomPaymentsGrid',
'type' => $type,
'paymentType' => 'Custom',
));
}
}
Is this possible to do (I am trying to avoid repetition)?
You should be able to, what did you try?
Assuming the $type is passed via GET, you can modify it in a beforeAction and the modified value will be applied to the target action with a request like
http://myhost.com/route/test?type=something
using the below, $type = "foo" in any action in this controller.
protected function beforeAction($action)
{
if (isset($_GET['type'])) {
$_GET['type'] = 'foo';
}
...
return parent::beforeAction($action);
}
public function actionTest($type)
{
# $type === 'foo'
...
}
Change the manipulation in beforeAction to satisfy whatever your requirements are.
I newbie in Laravel API. There is an update function which only allows users to update their own post. It worked. When users try to update other user's post, it alswo worked, but it shows the error like this image. Actually i want it show in response json.
I want to show message like this
{
"status": "error",
"message": "This action is unauthorized",
}
This is my code for PostController.
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json)
$post->content = $request->get('content', $post->content);
$post->save();
return fractal()
->item($post)
->transformWith(new PostTransformer)
->toArray();
}
This code for PostPolicy
public function update(User $user, Post $post)
{
return $user->ownsPost($post);
}
This is code for User model
public function ownsPost(Post $post)
{
return Auth::user()->id === $post->user->id;
}
This code for AuthServiceProvider
protected $policies = [
'App\Post' => 'App\Policies\PostPolicy',
];
Hope anyone can help me.
I'm using Laravel 5.4
In the app/Exceptions/Handler.php class you can change the render function like so
public function render($request, Exception $exception)
{
$preparedException = $this->prepareException($exception);
if ($preparedException instanceof HttpException) {
return response(
[
'message' => sprintf(
'%d %s',
$preparedException->getStatusCode(),
Response::$statusTexts[$preparedException->getStatusCode()]
),
'status' => $preparedException->getStatusCode()
],
$preparedException->getStatusCode(),
$preparedException->getHeaders()
);
}
return parent::render($request, $exception);
}
Or if you look further in the rendering, overriding the renderHttpException might be a little safer. This will remove the custom error pages in views/errors
protected function renderHttpException(HttpException $e)
{
return response(
[
'message' => sprintf(
'%d %s',
$e->getStatusCode(),
Response::$statusTexts[$e->getStatusCode()]
),
'status' => $e->getStatusCode()
],
$e->getStatusCode(),
$e->getHeaders()
);
}
I have following implicit route defined (Laravel 5.2)
// Handle locale
Route::group([
'prefix' => '{country}/{language}',
], function () {
Route::controller('user', 'UserController');
});
And here is my controller
class UserController extends BaseLocaleController
{
public function getIndex()
{
return view('user/index');
}
public function getProfile($slug)
{
echo $slug;die;
return view('user/view');
}
}
My URI Structure is
http://{host}/in/en/user/profile/manju
The problem here, my slug value is in instead of manju. Is there any URI pattern I need to apply?
How can make this work in Laravel 5.2. As you could see, I have country and language prefix in Route::group.
Just pass the $country, $language to the method
So it should be
public function getProfile($country, $language, $slug)
{
echo $slug;die;
return view('user/view');
}
I have to call a soap service using laravel and done so correctly. This soap service requires me to send a login request prior to sending any other request.
The code I'm using works, but I want to improve by removing the login from all the functions and creating one function.
I tried changing the following for one function:
public function getcard($cardid)
{
SoapWrapper::add(function ($service) {
$service
->name('IS')
->wsdl(app_path().'\giftcard.wsdl')
->trace(true);
});
$data = [
'UserName' => 'xxxx',
'Password' => 'xxxx',
];
$card = [
'CardId' => $cardid,
];
SoapWrapper::service('IS', function ($service) use ($data,$card) {
$service->call('Login', [$data]);
$cardinfo=$service->call('GetCard', [$card]);
dd($cardinfo->Card);
});
}
Into:
public function login()
{
SoapWrapper::add(function ($service) {
$service
->name('IS')
->wsdl(app_path().'\giftcard.wsdl')
->trace(true);
});
$data = [
'UserName' => 'xxxx',
'Password' => 'xxxx',
];
SoapWrapper::service('IS', function ($service) use ($data) {
return $service->call('Login', [$data]);
//$service->call('Login', [$data]);
//return $service;
});
}
public function getcard($cardid)
{
$this->login();
$card = [
'CardId' => $cardid,
];
$cardinfo=$service->call('GetCard', [$card]);
dd($card);
}
But this doesn't work. I also tried it with the commented out part, but that doesn't work. Both options result in an error that it didn't find 'service'.
I know it has something to do with oop, but don't know any other option.
I took this as an example, but I probably implemented it wrong?
So my question is: How do I reuse the login part for all other functions?
Your return statement in the login() method is within the scope of that closure. You need to return the result of the closure as well.
return SoapWrapper::service('IS', function ($service) use ($data) {
return $service->call('Login', [$data]);
});
EDIT:
To explain a little bit. You have a function:
SoapWrapper::service('IS' ,function() {}
Inside of a function : public function login()
If you need to return data from your login() method, and that data is contained within your SoapWrapper::service() method, then both methods need a return statement