Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

MdMostaFizurRahaman/ecommerce

29 stars
5 code files
View MdMostaFizurRahaman/ecommerce on GitHub

database/migrations/2021_10_30_003131_create_addresses_table.php

Open in GitHub
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
class CreateAddressesTable extends Migration
{
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->id();
$table->string('type', 45)->nullable();
$table->bigInteger('addressable_id')->unsigned();
$table->string('addressable_type');
$table->text('street')->nullable();
$table->string('city')->nullable()->index('address_city_index');
$table->string('state')->nullable()->index('address_state_index');
$table->string('country')->index('address_country_index');
$table->string('zipcode')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
//
}

app/Models/Address.php

Open in GitHub
class Address extends Model
{
//
public function addressable()
{
return $this->morphTo();
}
}

app/Traits/InteractsWithAddress.php

Open in GitHub
use App\Models\Address;
 
trait InteractsWithAddress
{
public function address()
{
return $this->morphMany(Address::class, 'addressable');
}
 
public function setAddress($address, $type)
{
$this->address()->updateOrCreate(
[
'type' => $type,
],
[
'street' => $address['street'],
'city' => $address['city'],
'state' => $address['state'] ?? null,
'zipcode' => $address['zipcode'] ?? null,
'country' => $address['country'],
]
);
}
}

app/Traits/CreateCustomer.php

Open in GitHub
use App\Models\Customer;
use App\Enums\AddressType;
 
trait CreateCustomer
{
public function createCustomer($request)
{
//
if (!empty($request->billingAddress)) {
$customer->setAddress($request->billingAddress, AddressType::BILLING_ADDRESS());
}
if (!empty($request->shippingAddress)) {
$customer->setAddress($request->shippingAddress, AddressType::SHIPPING_ADDRESS());
}
//
}
}

app/Traits/InteractsWithOrder.php

Open in GitHub
use App\Enums\AddressType;
use App\Models\Order;
 
trait InteractsWithOrder
{
public function createOrder($request)
{
//
if (!empty($request->billingAddress)) {
$order->setAddress($request->billingAddress, AddressType::BILLING_ADDRESS());
}
 
if (!empty($request->shippingAddress)) {
$order->setAddress($request->shippingAddress, AddressType::SHIPPING_ADDRESS());
}
//
}
//
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.