Table of Contents
{{ $product->name }}
Home PHP Framework Laravel How to use Laravel to develop an online group-sharing platform

How to use Laravel to develop an online group-sharing platform

Nov 03, 2023 pm 07:18 PM
laravel develop Online group booking

How to use Laravel to develop an online group-sharing platform

In recent years, with the rapid development of mobile Internet, various e-commerce platforms based on group buying have sprung up, among which e-commerce platforms focusing on group buying are becoming more and more popular. The more popular it is with consumers. This article will introduce how to use the Laravel framework to develop an online group-building platform and provide specific code examples.

1. Requirements Analysis

Before starting development, we need to conduct a requirements analysis to clarify which functional modules need to be developed. A complete group-building platform generally needs to include the following modules:

1. User management module

User registration, login, personal information management, etc.

2. Product management module

The administrator can add product information, including product name, price, inventory, etc.

3. Order management module

Users can select products for group purchase, place orders for purchase, and administrators can view and process orders.

4. Group management module

Users can create group activities or participate in existing group activities.

5. Payment module

supports multiple payment methods, and users can choose the payment method that suits them.

2. Environment setup

Before setting up the development environment, you need to install Composer first, and then run the following command in the command line:

composer create-project --prefer-dist laravel/laravel pin-tuan
Copy after login

This command will create a file named Laravel project for "pin-tuan".

Next, we need to configure the database, edit the ".env" file in the project root directory, and fill in the database-related information completely.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pin-tuan
DB_USERNAME=root
DB_PASSWORD=root
Copy after login

After completing the above steps, you can start writing program code.

3. Writing program code

1. User management module

(1) User registration

First, we need to add the registration route in the routing file :

Route::get('/register', 'AuthRegisterController@showRegistrationForm')->name('register');
Route::post('/register', 'AuthRegisterController@register');
Copy after login

Here we use Laravel’s own user authentication system to implement the user registration function. In the controller file, we only need to override the showRegistrationForm() and register() methods. The specific code is as follows:

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/dashboard';

    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    protected function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return redirect($this->redirectPath());
    }
}
Copy after login

(2) User login

Add login route in the routing file:

Route::get('/login', 'AuthLoginController@showLoginForm')->name('login');
Route::post('/login', 'AuthLoginController@login');
Route::post('/logout', 'AuthLoginController@logout')->name('logout');
Copy after login

Similarly, we use Laravel’s own user authentication system to Implement user login function. In the controller file, we only need to override the showLoginForm(), login() and logout() methods. The specific code is as follows:

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = '/dashboard';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm()
    {
        return view('auth.login');
    }

    protected function authenticated(Request $request, $user)
    {
        if (!$user->is_activated) {
            $this->guard()->logout();

            return redirect('/login')->withError('请先激活您的账号');
        }
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/login');
    }
}
Copy after login

(3) Personal information management

In the controller file, we only need to write an update() method to handle personal information update requests. The specific code is as follows:

public function update(Request $request)
{
    $user = Auth::user();

    $this->validate($request, [
        'name' => 'required|string|max:255|unique:users,name,' . $user->id,
        'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
        'password' => 'nullable|string|min:6|confirmed',
    ]);

    $user->name = $request->input('name');
    $user->email = $request->input('email');
    if ($request->has('password')) {
        $user->password = bcrypt($request->input('password'));
    }
    $user->save();

    return redirect()->back()->withSuccess('更新成功');
}
Copy after login

2. Product management module

(1) Product list

First, define the product model in the model file:

class Product extends Model
{
    protected $fillable = ['name', 'price', 'stock', 'description', 'image'];

    public function getAvatarAttribute($value)
    {
        return asset('storage/' . $value);
    }
}
Copy after login

Next, in the controller file, we write an index() method to display the product list. The specific code is as follows:

public function index()
{
    $products = Product::all();

    return view('product.index', compact('products'));
}
Copy after login

In the view file, we only need to traverse all the products and display them. The specific code is as follows:

@foreach ($products as $product)
    <div class="col-md-4">
        <div class="card mb-4 shadow-sm">
            <img  src="{{ $product- alt="How to use Laravel to develop an online group-sharing platform" >image }}" width="100%">
            <div class="card-body">
                <h5 id="product-name">{{ $product->name }}</h5>
                <p class="card-text">{{ $product->description }}</p>
                <div class="d-flex justify-content-between align-items-center">
                    <div class="btn-group">
                        <a href="{{ route('product.show', $product->id) }}" class="btn btn-sm btn-outline-secondary">查看</a>
                    </div>
                    <small class="text-muted">{{ $product->price }}元</small>
                </div>
            </div>
        </div>
    </div>
@endforeach
Copy after login

(2) Product details

In the controller file, we write a show() method to display product details. The specific code is as follows:

public function show($id)
{
    $product = Product::findOrFail($id);

    return view('product.show', compact('product'));
}
Copy after login

In the view file, we only need to display the detailed information of the product. The specific code is as follows:

<div class="row">
    <div class="col-md-6">
        <img  src="{{ $product- alt="How to use Laravel to develop an online group-sharing platform" >image }}" width="100%">
    </div>
    <div class="col-md-6">
        <h2 id="product-name">{{ $product->name }}</h2>
        <p>价格:{{ $product->price }}元</p>
        <p>库存:{{ $product->stock }}件</p>
        <form action="{{ route('product.buy', $product->id) }}" method="post">
            @csrf
            <div class="form-group">
                <label for="quantity">数量</label>
                <input type="number" name="quantity" class="form-control" min="1" max="{{ $product->stock }}" required>
            </div>
            <button type="submit" class="btn btn-primary">立即购买</button>
        </form>
    </div>
</div>
Copy after login

3. Order management module

(1) Order list

In the controller file, we write an index() method to display the order list . The specific code is as follows:

public function index()
{
    $orders = Order::where('user_id', Auth::id())->get();

    return view('order.index', compact('orders'));
}
Copy after login

In the view file, we only need to traverse all the orders and display them. The specific code is as follows:

@foreach ($orders as $order)
    <tr>
        <td>{{ $order->id }}</td>
        <td>{{ $order->product->name }}</td>
        <td>{{ $order->quantity }}</td>
        <td>{{ $order->price }}</td>
        <td>{{ $order->status }}</td>
    </tr>
@endforeach
Copy after login

(2) Place an order to purchase

In the controller file, we write a buy() method to implement the function of placing an order to purchase. The specific code is as follows:

public function buy(Request $request, $id)
{
    $product = Product::findOrFail($id);

    $this->validate($request, [
        'quantity' => 'required|integer|min:1|max:' . $product->stock,
    ]);

    $total_price = $product->price * $request->input('quantity');

    $order = new Order;
    $order->user_id = Auth::id();
    $order->product_id = $product->id;
    $order->quantity = $request->input('quantity');
    $order->price = $total_price;
    $order->status = '待支付';
    $order->save();

    // 跳转到第三方支付页面
    return redirect()->to('https://example.com/pay/' . $total_price);
}
Copy after login

4. Group management module

(1) Create a group activity

In the controller file, we write a create() method to Implement the function of creating group activities. The specific code is as follows:

public function create(Request $request)
{
    $product = Product::findOrFail($request->input('product_id'));

    $this->validate($request, [
        'group_size' => 'required|integer|min:2|max:' . $product->stock,
        'group_price' => 'required|numeric|min:0',
        'expired_at' => 'required|date|after:now',
    ]);

    $order = new Order;
    $order->user_id = Auth::id();
    $order->product_id = $product->id;
    $order->quantity = $request->input('group_size');
    $order->price = $request->input('group_price') * $request->input('group_size');
    $order->status = '待成团';
    $order->save();

    $group = new Group;
    $group->order_id = $order->id;
    $group->size = $request->input('group_size');
    $group->price = $request->input('group_price');
    $group->expired_at = $request->input('expired_at');
    $group->save();

    return redirect()->route('product.show', $product->id)->withSuccess('拼团创建成功');
}
Copy after login

(2) Participate in group activities

In the controller file, we write a join() method to implement the function of participating in group activities. The specific code is as follows:

public function join(Request $request, $id)
{
    $group = Group::findOrFail($id);

    $user_id = Auth::id();
    $product_id = $group->order->product_id;

    // 检查用户是否已参加该拼团活动
    $order = Order::where('user_id', $user_id)->where('product_id', $product_id)->where('status', '待成团')->first();
    if ($order) {
        return redirect()->route('product.show', $product_id)->withError('您已参加该拼团活动');
    }

    // 检查拼团活动是否已过期
    if ($group->expired_at < Carbon::now()) {
        return redirect()->route('product.show', $product_id)->withError('该拼团活动已过期');
    }

    // 检查拼团人数是否已满
    $count = Order::where('product_id', $product_id)->where('status', '待成团')->count();
    if ($count >= $group->size) {
        return redirect()->route('product.show', $product_id)->withError('该拼团活动已满员');
    }

    $order = new Order;
    $order->user_id = $user_id;
    $order->product_id = $product_id;
    $order->quantity = 1;
    $order->price = $group->price;
    $order->status = '待支付';
    $order->group_id = $group->id;
    $order->save();

    // 跳转到第三方支付页面
    return redirect()->to('https://example.com/pay/' . $group->price);
}
Copy after login

5. Payment module

Since this article is just a demo, we do not use the real third-party payment interface and can jump directly to the payment success page.

4. Summary

The above is the entire process of using the Laravel framework to develop an online group-building platform. Of course, this article only provides basic functional implementation, and actual development needs to be expanded and improved according to specific needs. I hope that readers can become more familiar with the application of the Laravel framework through this article, and that readers can continue to explore and try in actual development.

The above is the detailed content of How to use Laravel to develop an online group-sharing platform. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles