Make your Laravel controller THINNER using FormRequest

What is a Controller?

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return \Illuminate\View\View
*/
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
php artisan make:controller MyAwesomeController
<?php

namespace App\Http\Controllers;

use App\Coupon;
use App\Mail\OrderPlaced;
use App\Order;
use App\Product;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;

class CheckoutControllerController extends Controller
{
public function showCheckoutForm()
{
// getting already added to cart products
$data['selectedProducts'] = Session::get('productCart');

// returning view
return view('form.checkout', $data);
}

public function handleCheckOut(Request $request)
{
// setting validation rules for user's input
$formData = $request->validate([
'name' => 'required|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|confirmed',
'contact_number' => 'required',
'country' => 'required',
'shipping_address' => 'required',
'billing_address' => 'required',
'payment_method' => 'required|in:credit,cod',
'coupon' => 'nullable|exists:coupons,code',
'products.*.id' => 'required|integer|exists:products,id',
'products.*.price' => 'required|numeric',
'products.*.quantity' => 'required|numeric',
], [
'products.*.id.required' => 'The product field is required',
'products.*.id.integer' => 'The product field must be integer',
'products.*.id.exists' => 'The product do not exist',
]);

// registering user
$user = User::create([
'name' => $formData['name'],
'email' => $formData['email'],
'password' => bcrypt($formData['password']),
'country' => $formData['country'],
'contact_number' => $formData['contact_number'],
]);

// calculating total amount
$total = 0;
foreach ($request->get('products') as $product) {
$total += Product::find($product)->price;
}

// checking if coupon exists
if ($request->has('coupon')) {
$coupon = Coupon::find($request->get('coupon'));

$total = $total - (($coupon * $total) / 100);
}

// placing order
$order = Order::create([
'date' => now()->toDateString(),
'order_no' => time(),
'user_id' => $user->id,
'amount' => $total,
'shipping_address' => $request->get('shipping_address'),
'billing_address' => $request->get('billing_address'),
]);

$order->products()->attach($request->get('products'));

// sending mail to user
Mail::to($user->email)->send(new OrderPlaced($order));

// generating flash message
session()->flash('success', 'Order Placed Successfully');

// redirecting to home page
return redirect()->route('home');
}
}

FormRequest is your friend

php artisan make:request CheckoutRequest
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CheckoutRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false; // trough unauthorized error
return true; // no check, allowing to go further return auth()->check(); // returning true if user is logged in /* your custom logic to check user's role. If user has
the 'customer' role it will return true or false. */
return auth()->user()->hasRole('customer');
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|confirmed',
'contact_number' => 'required',
'country' => 'required',
'shipping_address' => 'required',
'billing_address' => 'required',
'payment_method' => 'required|in:credit,cod',
'coupon' => 'nullable|exists:coupons,code',
'products.*.id' => 'required|integer|exists:products,id',
'products.*.price' => 'required|numeric',
'products.*.quantity' => 'required|numeric'
];
}
/**
* @return array|string[]
*/
public function messages()
{
return [];
}
/**
* @return array|string[]
*/
public function messages()
{
return [
'products.*.id.required' => 'The product field is required',
'products.*.id.integer' => 'The product field must be integer',
'products.*.id.exists' => 'The product do not exist',

];
}
/* The defualt Illuminate\Http\Request is replaced by the App\Http\Requests\CheckoutRequest class */public function handleCheckOut(CheckoutRequest $request)
{

// all the validation and custom error messages are applied
$formData = $request->all();

// registering user
$user = User::create([
'name' => $formData['name'],
'email' => $formData['email'],
'password' => bcrypt($formData['password']),
'country' => $formData['country'],
'contact_number' => $formData['contact_number'],
]);

// calculating total amount
$total = 0;
foreach ($request->get('products') as $product) {
$total += Product::find($product)->price;
}

// checking if coupon exists
if ($request->has('coupon')) {
$coupon = Coupon::find($request->get('coupon'));

$total = $total - (($coupon * $total) / 100);
}

// placing order
$order = Order::create([
'date' => now()->toDateString(),
'order_no' => time(),
'user_id' => $user->id,
'amount' => $total,
'shipping_address' => $request->get('shipping_address'),
'billing_address' => $request->get('billing_address'),
]);

$order->products()->attach($request->get('products'));

// sending mail to user
Mail::to($user->email)->send(new OrderPlaced($order));

// generating flash message
session()->flash('success', 'Order Placed Successfully');

// redirecting to home page
return redirect()->route('home');
}
$formData = $request->all();
// In the controller using Illuminate\Http\Request $request object
$request->get('name')
// in the CheckoutRequest class
$this->get('name'); // no need to create object.
public function registerUser()
{
return User::create([
'name' => $this->get('name'),
'email' => $this->get('email'),
'password' => bcrypt($this->get('password')),
'country' => $this->get('country'),
'contact_number' => $this->get('contact_number')
]);
}
// registering user before using CheckoutRequest class$user = User::create([
'name' => $this->get('name'),
'email' => $this->get('email'),
'password' => bcrypt($this->get('password')),
'country' => $this->get('country'),
'contact_number' => $this->get('contact_number')
]);
// registering user after using CheckoutRequest class$user = $request->registerUser();
public function handleCheckOut(CheckoutRequest $request)
{
// registering user
$user = $request->registerUser();

// calculating total amount
$total = 0;
foreach ($request->get('products') as $product) {
$total += Product::find($product)->price;
}

// checking if coupon exists
if ($request->has('coupon')) {
$coupon = Coupon::find($request->get('coupon'));

$total = $total - (($coupon * $total) / 100);
}

// placing order
$order = Order::create([
'date' => now()->toDateString(),
'order_no' => time(),
'user_id' => $user->id,
'amount' => $total,
'shipping_address' => $request->get('shipping_address'),
'billing_address' => $request->get('billing_address'),
]);

$order->products()->attach($request->get('products'));

// sending mail to user
Mail::to($user->email)->send(new OrderPlaced($order));

// generating flash message
session()->flash('success', 'Order Placed Successfully');

// redirecting to home page
return redirect()->route('home');
}
private function getActualTotalAmount()
{
$total = 0;

foreach ($this->get('products') as $product) {
$total += Product::find($product)->price;
}

return $total;
}

private function getTotalAfterCouponDiscount()
{
$total = $this->getActualTotalAmount();

if ($this->has('coupon')) {
$coupon = Coupon::find($this->get('coupon'));

$total = $total - (($coupon * $total) / 100);
}

return $total;
}

public function placeOrder()
{
$order = Order::create([
'date' => now()->toDateString(),
'order_no' => time(),
'user_id' => $this->registerUser()->id,
'amount' => $this->getTotalAfterCouponDiscount(),
'shipping_address' => $this->get('shipping_address'),
'billing_address' => $this->get('billing_address'),
]);

$order->products()->attach($this->get('products'));

return $order;
}
public function handleCheckOut(CheckoutRequest $request)
{
// placing order
$order = $request->placeOrder();

// sending mail to user
Mail::to($request->get('email'))->send(new OrderPlaced($order));

// generating flash message
session()->flash('success', 'Order Placed Successfully');

// redirecting to home page
return redirect()->route('home');
}
<?php

namespace App\Http\Controllers;

use App\Http\Requests\CheckoutRequest;
use App\Mail\OrderPlaced;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;

class CheckoutControllerController extends Controller
{
public function showCheckoutForm()
{
// getting already added to cart products
$data['selectedProducts'] = Session::get('cart');

// returning view
return view('form.checkout', $data);
}

public function handleCheckOut(CheckoutRequest $request)
{
// placing order
$order = $request->placeOrder();

// sending mail to user
Mail::to($request->get('email'))->send(new OrderPlaced($order));

// generating flash message
session()->flash('success', 'Order Placed Successfully');

// redirecting to home page
return redirect()->route('home');
}
}
<?php

namespace App\Http\Requests;

use App\Coupon;
use App\Order;
use App\Product;
use App\User;
use Illuminate\Foundation\Http\FormRequest;

class CheckoutRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|confirmed',
'contact_number' => 'required',
'country' => 'required',
'shipping_address' => 'required',
'billing_address' => 'required',
'payment_method' => 'required|in:credit,cod',
'coupon' => 'nullable|exists:coupons,code',
'products.*.id' => 'required|integer|exists:products,id',
'products.*.price' => 'required|numeric',
'products.*.quantity' => 'required|numeric'
];
}

/**
* @return array|string[]
*/
public function messages()
{
return [
'products.*.id.required' => 'The product field is required',
'products.*.id.integer' => 'The product field must be integer',
'products.*.id.exists' => 'The product do not exist',
];
}

public function registerUser()
{
return User::create([
'name' => $this->get('name'),
'email' => $this->get('email'),
'password' => bcrypt($this->get('password')),
'country' => $this->get('country'),
'contact_number' => $this->get('contact_number')
]);
}

private function getActualTotalAmount()
{
$total = 0;

foreach ($this->get('products') as $product) {
$total += Product::find($product)->price;
}

return $total;
}

private function getTotalAfterCouponDiscount()
{
$total = $this->getActualTotalAmount();

if ($this->has('coupon')) {
$coupon = Coupon::find($this->get('coupon'));

$total = $total - (($coupon * $total) / 100);
}

return $total;
}

public function placeOrder()
{
$order = Order::create([
'date' => now()->toDateString(),
'order_no' => time(),
'user_id' => $this->registerUser()->id,
'amount' => $this->getTotalAfterCouponDiscount(),
'shipping_address' => $this->get('shipping_address'),
'billing_address' => $this->get('billing_address'),
]);

$order->products()->attach($this->get('products'));

return $order;
}
}

--

--

--

A software engineer from Bangladesh.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Building the Best Telegram Bot

The Docker Container Lifecycle | Docker Made Easy — part 3

High Availability Wordpress on AWS Elastic Beanstalk with Continuous Deployment (Part 1 of 2)

Working with partial mocks in PHPUnit 10

A Convenient Unity Project Management Tool

CS 373 Fall 2021: Srikar Ganti: Final Entry

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mehedi Hassan Sunny

Mehedi Hassan Sunny

A software engineer from Bangladesh.

More from Medium

How to run a Laravel project on git

Alea IT Solutions Best Web Development company in india

Laravel Vs. Codeigniter: A Head to Head Comparison

What is Laravel? What are the Main Features?

Converting Your Test Suite to PEST