KaranjitFYP
KaranjitFYP

Reputation: 103

laravel: Checking for existing records in my database

So i have a hotel booking system where that when the user clicks checkout, it should check if a record exists. The record is checked by; if it has the same check in day on that particular hotel. Currently i can select dates and the hotel and go straight to check out without any validation. I have two functions in (PostsController.php) which i need to compress into one as i found it would be much easier to complete, however im not sure really how to structure this.

PostsController.php:

    public function getAvailability (Request $request) {
             $user_id = $request->input('user_id');
             $checkIn = $request->input('checkIn');
             $checkOut = $request->input('checkOut');

             $post = Order::where('user_id', '=', $user_id)
                ->where ('checkIn', '=', $checkIn)
                ->where ('checkOut', '=', $checkOut)
                ->get();

            if(count($post) > 0) {
             return redirect()->route('posts.shopping-cart')->with('There is a clash');
             } else {
                    return redirect()->route('posts.checkout')->with('There is no clash');
                }
}
public function getCheckout(Request $request)
{
    if (!Session::has('cart')) {
        return view('shop.shopping-cart');
    }
    $oldCart = Session::get('cart');
    $cart = new Cart($oldCart);
    $total = $cart->totalPrice;
    $checkIn = $request->input('checkIn');
    $checkOut = $request->input('checkOut');
    return view('posts.checkout', ['total' => $total, 'checkIn' => $checkIn, 'checkOut' => 
    $checkOut]);
}

Here i want getAvailability to be used in getCheckout, I.E. i want getCheckout to be my main function. Also am i doing my function right ?

Upvotes: 0

Views: 186

Answers (1)

Daniel Petrovaliev
Daniel Petrovaliev

Reputation: 610

My suggestion here is to move business logic to your related model. For example you can extract this code:

$user_id = $request->input('user_id');
$checkIn = $request->input('checkIn');
$checkOut = $request->input('checkOut');

$post = Order::where('user_id', '=', $user_id)
        ->where ('checkIn', '=', $checkIn)
        ->where ('checkOut', '=', $checkOut)
        ->get();

into a function in your Order model which will be checkAvailability (or something similar) and then you will be able to use this function in your getAvailability and getCheckout in the PostsController.

Upvotes: 1

Related Questions