찾다
백엔드 개발PHP 튜토리얼Laravel 5.6의 CURD 작업(자세한 코드 예제)






이 기사에서는 laravel 5.6 버전의 기본 crud (생성, 읽기, 업데이트 및 삭제) 응용 프로그램 모듈을 공유하겠습니다. 아래 단계에 따라 laravel 5.6에서 CRUD 애플리케이션을 만들 수 있습니다.

Laravel 5.6의 CURD 작업(자세한 코드 예제)

Laravel은 다양한 고급 개발 기능을 갖춘 인기 있는 오픈 소스 PHP MVC 프레임워크입니다. laravel 5.6 애플리케이션의 학습자이거나 초보자라면 crud 애플리케이션에 대해 더 많이 알고 배우는 것이 항상 많은 도움이 됩니다. (관련 라라벨 영상 튜토리얼: "Latest Laravel Mall 실용 영상 튜토리얼")

아래에서는 삽입, 업데이트, 삭제, 보기 및 제품 페이징 예제를 작성하겠습니다. 새 제품을 만들고, 제품을 보고, 제품을 편집하고, 목록에서 제품을 제거하면 됩니다.

1단계: Laravel 5.6 설치

Laravel을 설치하려면 터미널에서 create-project 명령을 실행할 수 있습니다.

composer create-project --prefer-dist laravel/laravel blog

(관련 권장 사항: "작곡기를 통해 Laravel 프레임워크를 설치하는 방법?")

두 번째 단계: 데이터베이스 구성

설치가 완료된 후 데이터베이스 이름, 사용자 이름, 비밀번호 등 laravel 5.6의 crud 애플리케이션에 대한 데이터베이스를 구성합니다. 이제 .env 파일을 열고 다음과 같이 관련 정보를 입력해 보겠습니다.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

3단계: 제품 테이블 및 모델 생성

제품에 대한 crud 애플리케이션을 생성합니다. 따라서 Laravel 5.6 php artisan 명령을 사용하여 제품 테이블의 마이그레이션을 생성해야 합니다. 먼저 다음 명령을 사용하십시오:

php artisan make:migration create_products_table --create=products

이 명령을 실행한 후 database/migrations 경로에서 파일을 찾을 수 있으며 다음 코드는 제품 테이블을 생성하기 위해 마이그레이션 파일에 배치됩니다.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(&#39;products&#39;, function (Blueprint $table) {
            $table->increments(&#39;id&#39;);
            $table->string(&#39;name&#39;);
            $table->text(&#39;detail&#39;);
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(&#39;products&#39;);
    }
}

4단계: 리소스 경로 추가

이 단계에서는 제품 크루드 적용을 위한 리소스 경로를 추가해야 합니다. Routes/web.php 파일을 열고 다음 경로를 추가하십시오.

routes/web.php

Route::resource(&#39;products&#39;,&#39;ProductController&#39;);

5단계: ProductController 만들기

이제 새 컨트롤러 ProductController를 만들어야 합니다. 따라서 다음 명령을 실행하고 새 컨트롤러를 생성하십시오. 다음 컨트롤러는 리소스 컨트롤러를 만드는 데 사용됩니다.

Create ProductController

php artisan make:controller ProductController --resource --model=Product

다음 명령을 실행하면 app/Http/Controllers/ProductController.php 경로에서 새 파일을 찾을 수 있습니다.

이 컨트롤러에는 기본적으로 다음과 같이 7가지 메서드가 생성됩니다.

1)index()

2)create()

3)store()

4)show()

5)edit( )

6)update()

7)destroy()

그럼 아래 코드를 복사해서 ProductController.php 파일에 넣어보겠습니다.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::latest()->paginate(5);

        return view(&#39;products.index&#39;,compact(&#39;products&#39;))
            ->with(&#39;i&#39;, (request()->input(&#39;page&#39;, 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view(&#39;products.create&#39;);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        request()->validate([
            &#39;name&#39; => &#39;required&#39;,
            &#39;detail&#39; => &#39;required&#39;,
        ]);

        Product::create($request->all());

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product created successfully.&#39;);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return view(&#39;products.show&#39;,compact(&#39;product&#39;));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        return view(&#39;products.edit&#39;,compact(&#39;product&#39;));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
         request()->validate([
            &#39;name&#39; => &#39;required&#39;,
            &#39;detail&#39; => &#39;required&#39;,
        ]);

        $product->update($request->all());

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product updated successfully&#39;);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route(&#39;products.index&#39;)
                        ->with(&#39;success&#39;,&#39;Product deleted successfully&#39;);
    }
}

좋아, 다음 명령을 실행하면 app/Product.php를 찾고 다음 내용을 Product.php 파일에 넣을 수 있습니다:

app/Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        &#39;name&#39;, &#39;detail&#39;
    ];
}

6단계: 블레이드 파일 생성

이제 마지막 단계로 이동합니다. 이 단계에서는 블레이드 파일을 생성하기만 하면 됩니다. 따라서 우리는 주로 레이아웃 파일을 생성한 다음 새 폴더 "products"를 생성하고 crud 앱의 블레이드 파일을 생성해야 합니다. 마지막으로 다음 블레이드 파일을 생성해야 합니다.

1)layout.blade.php

2)index.blade.php

3)show.blade.php

4)form.blade.php

5 ) create.blade .php

6) edit.blade.php

다음 파일을 생성하고 다음 코드를 넣어보겠습니다.

resources/views/products/layout.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 5.6 CRUD Application</title>
	<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="container">
    @yield(&#39;content&#39;)
</div>

</body>
</html>

resources/views/products/index.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2 id="Laravel-nbsp-nbsp-CRUD-nbsp-Example-nbsp-from-nbsp-scratch">Laravel 5.6 CRUD Example from scratch</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route(&#39;products.create&#39;) }}"> Create New Product</a>
            </div>
        </div>
    </div>

    @if ($message = Session::get(&#39;success&#39;))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->detail }}</td>
            <td>
                <form action="{{ route(&#39;products.destroy&#39;,$product->id) }}" method="POST">

                    <a class="btn btn-info" href="{{ route(&#39;products.show&#39;,$product->id) }}">Show</a>
                    <a class="btn btn-primary" href="{{ route(&#39;products.edit&#39;,$product->id) }}">Edit</a>

                    @csrf
                    @method(&#39;DELETE&#39;)

   
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>

    {!! $products->links() !!}

@endsection

resources/views/products/show.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2 id="nbsp-Show-nbsp-Product"> Show Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route(&#39;products.index&#39;) }}"> Back</a>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $product->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $product->detail }}
            </div>
        </div>
    </div>
@endsection

resources/views/products/ create.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2 id="Add-nbsp-New-nbsp-Product">Add New Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route(&#39;products.index&#39;) }}"> Back</a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route(&#39;products.store&#39;) }}" method="POST">
        @csrf

         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </form>

@endsection

resources/views/products/edit.blade.php

@extends(&#39;products.layout&#39;)

@section(&#39;content&#39;)
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2 id="Edit-nbsp-Product">Edit Product</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route(&#39;products.index&#39;) }}"> Back</a>
            </div>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route(&#39;products.update&#39;,$product->id) }}" method="POST">
        @csrf
        @method(&#39;PUT&#39;)

         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $product->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $product->detail }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </form>

@endsection

이제 crud 애플리케이션 예제를 실행할 준비가 되었으므로 다음 명령을 실행하여 빠르게 실행하세요.

php artisan serve

마지막으로 다음 명령을 실행하세요. 보고 테스트하려면 브라우저에서 다음 URL을 열 수 있습니다.

http://localhost:8000/products

이 기사는 Laravel 5.6의 CURD 작업, 즉 생성, 읽기, 업데이트 및 삭제 작업에 대한 내용입니다. 도움이 필요한 친구들에게 도움이 되기를 바랍니다. !






위 내용은 Laravel 5.6의 CURD 작업(자세한 코드 예제)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP의 지속적인 사용 : 지구력의 이유PHP의 지속적인 사용 : 지구력의 이유Apr 19, 2025 am 12:23 AM

여전히 인기있는 것은 사용 편의성, 유연성 및 강력한 생태계입니다. 1) 사용 편의성과 간단한 구문은 초보자에게 첫 번째 선택입니다. 2) 웹 개발, HTTP 요청 및 데이터베이스와의 우수한 상호 작용과 밀접하게 통합되었습니다. 3) 거대한 생태계는 풍부한 도구와 라이브러리를 제공합니다. 4) 활성 커뮤니티와 오픈 소스 자연은 새로운 요구와 기술 동향에 맞게 조정됩니다.

PHP 및 Python : 유사점과 차이점을 탐구합니다PHP 및 Python : 유사점과 차이점을 탐구합니다Apr 19, 2025 am 12:21 AM

PHP와 Python은 웹 개발, 데이터 처리 및 자동화 작업에 널리 사용되는 고급 프로그래밍 언어입니다. 1.PHP는 종종 동적 웹 사이트 및 컨텐츠 관리 시스템을 구축하는 데 사용되며 Python은 종종 웹 프레임 워크 및 데이터 과학을 구축하는 데 사용됩니다. 2.PHP는 Echo를 사용하여 콘텐츠를 출력하고 Python은 인쇄를 사용합니다. 3. 객체 지향 프로그래밍을 지원하지만 구문과 키워드는 다릅니다. 4. PHP는 약한 유형 변환을 지원하는 반면, 파이썬은 더 엄격합니다. 5. PHP 성능 최적화에는 Opcache 및 비동기 프로그래밍 사용이 포함되며 Python은 Cprofile 및 비동기 프로그래밍을 사용합니다.

PHP와 Python : 다른 패러다임이 설명되었습니다PHP와 Python : 다른 패러다임이 설명되었습니다Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python : 그들의 역사에 깊은 다이빙PHP와 Python : 그들의 역사에 깊은 다이빙Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP와 Python 중에서 선택 : 가이드PHP와 Python 중에서 선택 : 가이드Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP 및 프레임 워크 : 언어 현대화PHP 및 프레임 워크 : 언어 현대화Apr 18, 2025 am 12:14 AM

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

PHP의 영향 : 웹 개발 및 그 이상PHP의 영향 : 웹 개발 및 그 이상Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?Apr 17, 2025 am 12:25 AM

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기