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

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

Mar 01, 2019 am 11:24 AM






이 기사에서는 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>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> 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>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>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으로 문의하세요.

핫 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를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? Apr 01, 2025 pm 03:12 PM

PHP 개발에서 PHP의 CURL 라이브러리를 사용하여 JSON 데이터를 보내면 종종 외부 API와 상호 작용해야합니다. 일반적인 방법 중 하나는 컬 라이브러리를 사용하여 게시물을 보내는 것입니다 ...

See all articles