Home » Php » php – how to update order status by admin in laravel 5.8?

php – how to update order status by admin in laravel 5.8?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m a beginner in laravel and I’m weak in programming but I’m trying to improve in learning programming and I’m trying to make an Ecommerce site so my problem is about order status in admin section (admin can update order status) I can’t found a solution for this so I need help please

When I click update I have this error:

ErrorException (E_NOTICE)
Undefined index: id
  public function findOrderByNumber($orderNumber)
    {
        return Order::where('order_number', $orderNumber)->first();
    }
     /**
     * @param array $params
     * @return mixed
     */
    public function updateOrder(array $params)
    {
        $order = $this->findOrderById($params['id']);

        $collection = collect($params)->except('_token');




        $order->update();



        return $order;
    }

I want admin can change and update order status in edit order status page and order status change in order:index.blade.php view
so how can I resolve that? thank you very much

This is the code:

order contract:

<?php

namespace App\Contracts;

interface OrderContract
{
    public function storeOrderDetails($params);

    public function listOrders(string $order = 'id', string $sort = 'desc', array $columns = ['*']);
 /**
     * @param int $id
     * @return mixed
     */
    public function findOrderById(int $id);

    public function findOrderByNumber($orderNumber);
       /**
     * @param array $params
     * @return mixed
     */
    public function updateOrder(array $params);

    /**
     * @param $id
     * @return bool
     */
    public function deleteOrder($orderNumber);
}

order repository:

<?php

namespace App\Repositories;

use Cart;
use App\Models\Order;
use App\Models\Product;
use App\Models\OrderItem;
use App\Contracts\OrderContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;

class OrderRepository extends BaseRepository implements OrderContract
{
    public function __construct(Order $model)
    {
        parent::__construct($model);
        $this->model = $model;
    }

    public function storeOrderDetails($params)
    {
        $order = Order::create([
            'order_number'      =>  'ORD-'.strtoupper(uniqid()),
            'user_id'           => auth()->user()->id,
            'status'            =>  'pending',
            'grand_total'       =>  Cart::getSubTotal(),
            'item_count'        =>  Cart::getTotalQuantity(),
            'payment_status'    =>  0,
            'payment_method'    =>  null,
            'first_name'        =>  $params['first_name'],
            'last_name'         =>  $params['last_name'],
            'address'           =>  $params['address'],
            'city'              =>  $params['city'],
            'country'           =>  $params['country'],
            'post_code'         =>  $params['post_code'],
            'phone_number'      =>  $params['phone_number'],
            'notes'             =>  $params['notes']
        ]);

        if ($order) {

            $items = Cart::getContent();

            foreach ($items as $item)
            {
                // A better way will be to bring the product id with the cart items
                // you can explore the package documentation to send product id with the cart
                $product = Product::where('name', $item->name)->first();



                $orderItem = new OrderItem([
                    'product_id'    =>  $product->id,
                    'quantity'      =>  $item->quantity,
                    'price'         =>  $item->getPriceSum()
                ]);
                $product=Product::where('id', '=', $orderItem->product_id)->decrement('quantity',$item->quantity);
                $order->items()->save($orderItem);

            }
        }

        return $order;
    }

    public function listOrders(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
    {
        return $this->all($columns, $order, $sort);
    }
     /**
     * @param int $id
     * @return mixed
     * @throws ModelNotFoundException
     */
    public function findOrderById(int $id)
    {
        try {
            return $this->findOneOrFail($id);

        } catch (ModelNotFoundException $e) {

            throw new ModelNotFoundException($e);
        }

    }

    public function findOrderByNumber($orderNumber)
    {
        return Order::where('order_number', $orderNumber)->first();
    }
     /**
     * @param array $params
     * @return mixed
     */
    public function updateOrder(array $params)
    {
        $order = $this->findOrderById($params['id']);

        $collection = collect($params)->except('_token');




        $order->update();



        return $order;
    }
     /**
     * @param $id
     * @return bool|mixed
     */
    public function deleteOrder($orderNumber)
    {
        $order = $this->findOrderByNumber($orderNumber);

        $order->delete();

        return $order;
    }
}

order controller:

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use\App\Models\Order;
use App\Contracts\OrderContract;
use App\Http\Controllers\BaseController;
class OrderController extends BaseController
{
    protected $orderRepository;

    public function __construct(OrderContract $orderRepository)
    {
        $this->orderRepository = $orderRepository;
    }

    public function index()
    {
        $orders = $this->orderRepository->listOrders();
        $this->setPageTitle('Orders', 'List of all orders');
        return view('admin.orders.index', compact('orders'));
    }

    public function show($orderNumber)
    {
        $order = $this->orderRepository->findOrderByNumber($orderNumber);

        $this->setPageTitle('Order Details', $orderNumber);
        return view('admin.orders.show', compact('order'));
    }
    public function edit($orderNumber)
    {
        $order = $this->orderRepository->findOrderByNumber($orderNumber);
        $orders=Order::where('order_number', $orderNumber)->first();
        $this->setPageTitle('Orders Status', 'Edit Order Status');
        return view('admin.orders.edit', compact('order','orders'));
    }

    public function update(Request $request)
    {
        $params = $request->except('_token');


        $order = $this->orderRepository->updateOrder($params);

        if (!$order) {
            return $this->responseRedirectBack('Error occurred while updating order status.', 'error', true, true);
        }
        return $this->responseRedirect('admin.orders.index', 'Order Status updated successfully' ,'success',false, false);
    }
      /**
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete($orderNumber)
    {
        $order = $this->orderRepository->deleteOrder($orderNumber);

        if (!$order) {
            return $this->responseRedirectBack('Error occurred while deleting Order.', 'error', true, true);
        }
        return $this->responseRedirect('admin.orders.index', 'Order deleted successfully' ,'success',false, false);
    }

    }


order:index.blade.php

@extends('admin.app')
@section('title') {{ $pageTitle }} @endsection
@section('content')
    <div class="app-title">
        <div>
            <h1><i class="fa fa-bar-chart"></i> {{ $pageTitle }}</h1>
            <p>{{ $subTitle }}</p>
        </div>
    </div>
    @include('admin.partials.flash')
    <div class="row">
        <div class="col-md-12">
            <div class="tile">
                <div class="tile-body">
                    <table class="table table-hover table-bordered" id="sampleTable">
                        <thead>
                        <tr>
                            <th> Order Number </th>
                            <th> Placed By </th>
                            <th class="text-center"> Total Amount </th>
                            <th class="text-center"> Items Qty </th>
                            <th class="text-center"> Payment Status </th>
                            <th class="text-center"> Status </th>
                            <th style="width:100px; min-width:100px;" class="text-center text-danger"><i class="fa fa-bolt"> </i></th>
                        </tr>
                        </thead>
                        <tbody>
                        @foreach($orders as $order)
                            <tr>
                                <td>{{ $order->order_number }}</td>
                                <td>{{ $order->user->fullName }}</td>
                                <td class="text-center">{{ config('settings.currency_symbol') }}{{ $order->grand_total }}</td>
                                <td class="text-center">{{ $order->item_count }}</td>
                                <td class="text-center">
                                    @if ($order->payment_status == 1)
                                        <span class="badge badge-success">Completed</span>
                                    @else
                                        <span class="badge badge-danger">Not Completed</span>
                                    @endif
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-success">{{ $order->status }}</span>

                                </td>
                                <td class="text-center">
                                    <div class="btn-group" role="group" aria-label="Second group">

                                        <a href="{{ route('admin.orders.show', $order->order_number) }}" class="btn btn-sm btn-info"><i class="fa fa-eye"></i></a>
                                        <a href="{{ route('admin.orders.edit', $order->order_number) }}" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></a>
                                        <a href="{{ route('admin.orders.delete', $order->order_number) }}" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></a>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection
@push('scripts')
    <script type="text/javascript" src="{{ asset('backend/js/plugins/jquery.dataTables.min.js') }}"></script>
    <script type="text/javascript" src="{{ asset('backend/js/plugins/dataTables.bootstrap.min.js') }}"></script>
    <script type="text/javascript">$('#sampleTable').DataTable();</script>
@endpush

order:edit.blade.php

@extends('admin.app')
@section('title') {{ $pageTitle }} @endsection
@section('content')
    <div class="app-title">
        <div>
            <h1><i class="fa fa-briefcase"></i> {{ $pageTitle }}</h1>
        </div>
    </div>
    @include('admin.partials.flash')
    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="tile">
                <h3 class="tile-title">{{ $subTitle }}</h3>
                <form action="{{ route('admin.orders.update') }}" method="POST" role="form" enctype="multipart/form-data">
                    @csrf
                    <div class="tile-body">
                        <div class="form-group">

                   <select name="order" id="order"  >

                    <option value="Pending" selected >Pending</option>

                     <option value="Completed"  selected >Completed</option>

                     <option value=" Processing" selected >Processing</option>

                     <option value="Decline"  selected >Decline</option>


                   </select>

                     </div>
                    </div>
                    <div class="tile-footer">
                        <button class="btn btn-success" type="submit"><i class="fa fa-fw fa-lg fa-check-circle"></i>Update Order Status</button>
                        &nbsp;&nbsp;&nbsp;
                        <a class="btn btn-secondary" href="{{ route('admin.orders.index') }}"><i class="fa fa-fw fa-lg fa-times-circle"></i>Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection
@push('scripts')

@endpush


route:

 Route::group(['prefix' => 'orders'], function () {
        Route::get('/', 'Admin\[email protected]')->name('admin.orders.index');
        Route::get('/{order}/show', 'Admin\[email protected]')->name('admin.orders.show');
        Route::get('/{id}/edit', 'Admin\[email protected]')->name('admin.orders.edit');
        Route::post('/update', 'Admin\[email protected]')->name('admin.orders.update');
        Route::get('/{id}/delete', 'Admin\[email protected]')->name('admin.orders.delete');
     });
How to&Answers: