• \n
    \n @yield('content')\n <\/div>\n<\/body>\n<\/html><\/pre>

    6. Set Up Routes<\/strong><\/h3>

    Open routes\/web.php<\/code> and add:<\/p>

     use App\\Http\\Controllers\\PostController;\n\nRoute::resource('posts', PostController::class)->only(['index', 'show']);<\/pre>

    We'll restrict to index<\/code> and show<\/code> for public access. Admin features (create, edit) can come later.<\/p>


    7. Add the Show Method for Single Posts<\/strong><\/h3>

    In PostController.php<\/code> , add the show<\/code> method:<\/p>

     public function show($slug)\n{\n    $post = Post::where('slug', $slug)->where('is_published', true)->firstOrFail();\n    return view('posts.show', compact('post'));\n}<\/pre>

    Create resources\/views\/posts\/show.blade.php<\/code> :<\/p>

     @extends('layouts.app')\n\n@section('content')\n    ← Back to Blog<\/a>\n    

    {{ $post->title }}<\/h1>\n

    {{ $post->content }}<\/p>\n Published on {{ $post->created_at->format('M d, Y') }}<\/small>\n@endsection<\/pre>


    8. Add a Basic Admin Section (Optional)<\/strong><\/h3>

    To create or edit posts, you'll need authentication and an admin area.<\/p>

    Install Laravel Breeze for simple auth:<\/p>

     composer require laravel\/breeze --dev\nphp artisan breeze:install\nnpm install && npm run dev\nphp artisan migrate<\/pre>

    Now, protect your admin routes. Generate a controller for admin actions:<\/p>

     php artisan make:controller Admin\/PostController<\/pre>

    Add routes in web.php<\/code> :<\/p>

     use App\\Http\\Controllers\\Admin\\PostController as AdminPostController;\n\nRoute::middleware(['auth'])->prefix('admin')->group(function () {\n    Route::resource('posts', AdminPostController::class);\n});<\/pre>

    Then implement create<\/code> , store<\/code> , edit<\/code> , update<\/code> , and destroy<\/code> methods in the admin controller, and create corresponding Blade forms.<\/p>

    Add a slug<\/code> field when storing posts—use something like:<\/p>

     $post = Post::create([\n    'title' => $request->title,\n    'content' => $request->content,\n    'slug' => Str::slug($request->title),\n    'is_published' => $request->is_published,\n]);<\/pre>
    \n

    9. Optional Enhancements<\/strong>\n<\/h3>\n

    Once the basics are working, consider adding:<\/p>\n

      \n
    • Markdown support<\/strong> using a package like parsedown<\/code>\n<\/li>\n
    • Image uploads<\/strong> with Laravel's filesystem<\/li>\n
    • Categories or tags<\/strong> with relationships<\/li>\n
    • SEO-friendly meta tags<\/strong>\n<\/li>\n
    • Comments system<\/strong> (with moderation)<\/li>\n
    • Search functionality<\/strong>\n<\/li>\n<\/ul>\n
      \n

      Final Notes<\/h3>\n

      You now have a working Laravel blog with:<\/p>\n

        \n
      • A public blog listing<\/li>\n
      • Individual post pages<\/li>\n
      • A database-backed model<\/li>\n
      • Simple routing and views<\/li>\n
      • Optional admin area with authentication<\/li>\n<\/ul>\n

        The key is to build incrementally. Start with core features, test each step, then expand.<\/p>\n

        Basically, that's how you build a blog from scratch in Laravel—no magic, just solid MVC structure and Laravel's elegant syntax.<\/p>"}

        亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

        目錄
        2. Configure the Database
        3. Create the Blog Post Model and Migration
        4. Build the Post Controller
        5. Create Blade Views
        6. Set Up Routes
        7. Add the Show Method for Single Posts
        8. Add a Basic Admin Section (Optional)
        Final Notes
        首頁 php框架 Laravel 如何與Laravel從頭開始建立博客?

        如何與Laravel從頭開始建立博客?

        Aug 02, 2025 am 10:16 AM

        安裝並創(chuàng)建Laravel項(xiàng)目,使用composer create-project命令初始化blog項(xiàng)目並啟動開發(fā)服務(wù)器;2. 配置數(shù)據(jù)庫,在.env文件中設(shè)置MySQL連接信息並創(chuàng)建blog數(shù)據(jù)庫;3. 創(chuàng)建Post模型和遷移文件,定義title、content、slug、is_published等字段並執(zhí)行遷移;4. 生成PostController資源控制器,在index方法中查詢已發(fā)布的文章並分頁顯示;5. 使用Blade模板引擎創(chuàng)建佈局和視圖文件,包括文章列表和詳情頁面;6. 在web.php中註冊資源路由,僅開放index和show方法供公眾訪問;7. 實(shí)現(xiàn)show方法通過slug查找並展示單篇文章;8. 可選地安裝Laravel Breeze實(shí)現(xiàn)認(rèn)證,創(chuàng)建管理員專用路由和控制器處理文章的增刪改查;9. 進(jìn)一步優(yōu)化功能,如添加Markdown解析、圖片上傳、分類標(biāo)籤、SEO支持、評論系統(tǒng)和搜索功能;最終你將獲得一個(gè)具備基礎(chǔ)功能、基於MVC架構(gòu)、可擴(kuò)展的Laravel博客系統(tǒng),以完整句?結(jié)束。

        How to build a blog with Laravel from scratch?

        Building a blog with Laravel from scratch is a great way to learn the framework while creating something practical. Laravel provides powerful tools for routing, authentication, database management, and templating—perfect for a blog. Here's a step-by-step guide to help you build a simple but functional blog.

        How to build a blog with Laravel from scratch?

        1. Set Up Laravel and Create the Project

        First, make sure you have PHP, Composer, and a database (like MySQL) installed.

        Run this command in your terminal to create a new Laravel project:

        How to build a blog with Laravel from scratch?
         composer create-project laravel/laravel blog

        Navigate into the project:

         cd blog

        Start the development server to verify it works:

        How to build a blog with Laravel from scratch?
         php artisan serve

        Visit http://localhost:8000 in your browser. You should see the Laravel welcome page.


        2. Configure the Database

        Open .env in the root directory and update the database settings:

         DB_CONNECTION=mysql
        DB_HOST=127.0.0.1
        DB_PORT=3306
        DB_DATABASE=blog
        DB_USERNAME=root
        DB_PASSWORD=

        Make sure you've created the blog database in MySQL (or your preferred DB).


        3. Create the Blog Post Model and Migration

        Run the following Artisan command to generate a model and migration for blog posts:

         php artisan make:model Post -mf

        The -m creates a migration, and -f adds a factory (optional).

        Open the migration file in database/migrations/xxxx_create_posts_table.php and define the fields:

         Schema::create(&#39;posts&#39;, function (Blueprint $table) {
            $table->id();
            $table->string(&#39;title&#39;);
            $table->text(&#39;content&#39;);
            $table->string(&#39;slug&#39;)->unique();
            $table->boolean(&#39;is_published&#39;)->default(false);
            $table->timestamps();
        });

        Run the migration:

         php artisan migrate

        4. Build the Post Controller

        Generate a controller for handling blog posts:

         php artisan make:controller PostController --resource

        This creates a resource controller with methods like index , create , store , etc.

        Now, go to app/Http/Controllers/PostController.php and start filling in the logic.

        For now, let's set up the index method to display published posts:

         use App\Models\Post;
        
        public function index()
        {
            $posts = Post::where(&#39;is_published&#39;, true)->latest()->paginate(5);
            return view(&#39;posts.index&#39;, compact(&#39;posts&#39;));
        }

        5. Create Blade Views

        Create a views directory for posts: resources/views/posts/

        Create index.blade.php :

         @extends(&#39;layouts.app&#39;)
        
        @section(&#39;content&#39;)
            <h1>Blog Posts</h1>
            @foreach ($posts as $post)
                <article>
                    <h2><a href="{{ route(&#39;posts.show&#39;, $post->slug) }}">{{ $post->title }}</a></h2>
                    <p>{{ Str::limit($post->content, 150) }}</p>
                    <small>Published on {{ $post->created_at->format(&#39;M d, Y&#39;) }}</small>
                </article>
                <hr />
            @endforeach
        
            {{ $posts->links() }}
        @endsection

        You'll also need a basic layout. Create resources/views/layouts/app.blade.php :

         <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>My Laravel Blog</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        </head>
        <body>
            <div class="container mt-4">
                @yield(&#39;content&#39;)
            </div>
        </body>
        </html>

        6. Set Up Routes

        Open routes/web.php and add:

         use App\Http\Controllers\PostController;
        
        Route::resource(&#39;posts&#39;, PostController::class)->only([&#39;index&#39;, &#39;show&#39;]);

        We'll restrict to index and show for public access. Admin features (create, edit) can come later.


        7. Add the Show Method for Single Posts

        In PostController.php , add the show method:

         public function show($slug)
        {
            $post = Post::where(&#39;slug&#39;, $slug)->where(&#39;is_published&#39;, true)->firstOrFail();
            return view(&#39;posts.show&#39;, compact(&#39;post&#39;));
        }

        Create resources/views/posts/show.blade.php :

         @extends(&#39;layouts.app&#39;)
        
        @section(&#39;content&#39;)
            <a href="{{ route(&#39;posts.index&#39;) }}">← Back to Blog</a>
            <h1>{{ $post->title }}</h1>
            <p>{{ $post->content }}</p>
            <small>Published on {{ $post->created_at->format(&#39;M d, Y&#39;) }}</small>
        @endsection

        8. Add a Basic Admin Section (Optional)

        To create or edit posts, you'll need authentication and an admin area.

        Install Laravel Breeze for simple auth:

         composer require laravel/breeze --dev
        php artisan breeze:install
        npm install && npm run dev
        php artisan migrate

        Now, protect your admin routes. Generate a controller for admin actions:

         php artisan make:controller Admin/PostController

        Add routes in web.php :

         use App\Http\Controllers\Admin\PostController as AdminPostController;
        
        Route::middleware([&#39;auth&#39;])->prefix(&#39;admin&#39;)->group(function () {
            Route::resource(&#39;posts&#39;, AdminPostController::class);
        });

        Then implement create , store , edit , update , and destroy methods in the admin controller, and create corresponding Blade forms.

        Add a slug field when storing posts—use something like:

         $post = Post::create([
            &#39;title&#39; => $request->title,
            &#39;content&#39; => $request->content,
            &#39;slug&#39; => Str::slug($request->title),
            &#39;is_published&#39; => $request->is_published,
        ]);

        9. Optional Enhancements

        Once the basics are working, consider adding:

        • Markdown support using a package like parsedown
        • Image uploads with Laravel's filesystem
        • Categories or tags with relationships
        • SEO-friendly meta tags
        • Comments system (with moderation)
        • Search functionality

        Final Notes

        You now have a working Laravel blog with:

        • A public blog listing
        • Individual post pages
        • A database-backed model
        • Simple routing and views
        • Optional admin area with authentication

        The key is to build incrementally. Start with core features, test each step, then expand.

        Basically, that's how you build a blog from scratch in Laravel—no magic, just solid MVC structure and Laravel's elegant syntax.

        以上是如何與Laravel從頭開始建立博客?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

        本網(wǎng)站聲明
        本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

        熱AI工具

        Undress AI Tool

        Undress AI Tool

        免費(fèi)脫衣圖片

        Undresser.AI Undress

        Undresser.AI Undress

        人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

        AI Clothes Remover

        AI Clothes Remover

        用於從照片中去除衣服的線上人工智慧工具。

        Clothoff.io

        Clothoff.io

        AI脫衣器

        Video Face Swap

        Video Face Swap

        使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

        熱工具

        記事本++7.3.1

        記事本++7.3.1

        好用且免費(fèi)的程式碼編輯器

        SublimeText3漢化版

        SublimeText3漢化版

        中文版,非常好用

        禪工作室 13.0.1

        禪工作室 13.0.1

        強(qiáng)大的PHP整合開發(fā)環(huán)境

        Dreamweaver CS6

        Dreamweaver CS6

        視覺化網(wǎng)頁開發(fā)工具

        SublimeText3 Mac版

        SublimeText3 Mac版

        神級程式碼編輯軟體(SublimeText3)

        熱門話題

        Laravel 教程
        1597
        29
        PHP教程
        1488
        72
        與Laravel中的樞軸表合作多對多關(guān)係 與Laravel中的樞軸表合作多對多關(guān)係 Jul 07, 2025 am 01:06 AM

        toworkeffectivelywithpivottablesinlaravel,firstAccessPivotDatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdatee XistingPivot(),ManageraliationShipsviadeTach()andsync(),andusecustompivotModelSwhenNeed.1.UseWithPivot()toincludespecificcol

        通過Laravel發(fā)送不同類型的通知 通過Laravel發(fā)送不同類型的通知 Jul 06, 2025 am 12:52 AM

        laravelProvidesLeanAndFlexibleWayTosendificationsViamultiplipliplipliplikeMail,SMS,In-Appalerts,and-Appalerts,andPushNotifications.youdefineNotificationChannelsinthelsinthevia()MethodofanotificationClass,andimpecificementpecificementpecificementpecificemmethodssliketomail()

        了解Laravel的依賴注入? 了解Laravel的依賴注入? Jul 05, 2025 am 02:01 AM

        依賴注入在Laravel中通過服務(wù)容器自動處理類的依賴關(guān)係,無需手動new對象。其核心是構(gòu)造函數(shù)注入和方法注入,如控制器中自動傳入Request實(shí)例。 Laravel通過類型提示解析依賴,遞歸創(chuàng)建所需對象。綁定接口與實(shí)現(xiàn)可通過服務(wù)提供者使用bind方法,或singleton綁定單例。使用時(shí)需確保類型提示、避免構(gòu)造函數(shù)複雜化、謹(jǐn)慎使用上下文綁定,並理解自動解析規(guī)則。掌握這些可提升代碼靈活性與維護(hù)性。

        優(yōu)化Laravel應(yīng)用程序性能的策略 優(yōu)化Laravel應(yīng)用程序性能的策略 Jul 09, 2025 am 03:00 AM

        Laravel性能優(yōu)化可通過四個(gè)核心方向提升應(yīng)用效率。 1.使用緩存機(jī)制減少重複查詢,通過Cache::remember()等方法存儲不常變化的數(shù)據(jù),降低數(shù)據(jù)庫訪問頻率;2.從模型到查詢語句進(jìn)行數(shù)據(jù)庫優(yōu)化,避免N 1查詢、指定字段查詢、添加索引、分頁處理及讀寫分離,減少瓶頸;3.將耗時(shí)操作如郵件發(fā)送、文件導(dǎo)出放入隊(duì)列異步處理,利用Supervisor管理工作者並設(shè)置重試機(jī)制;4.合理使用中間件與服務(wù)提供者,避免複雜邏輯和不必要的初始化代碼,延遲加載服務(wù)以提升啟動效率。

        管理數(shù)據(jù)庫狀態(tài)進(jìn)行Laravel測試 管理數(shù)據(jù)庫狀態(tài)進(jìn)行Laravel測試 Jul 13, 2025 am 03:08 AM

        在Laravel測試中管理數(shù)據(jù)庫狀態(tài)的方法包括使用RefreshDatabase、選擇性播種數(shù)據(jù)、謹(jǐn)慎使用事務(wù)和必要時(shí)手動清理。 1.使用RefreshDatabasetrait自動遷移數(shù)據(jù)庫結(jié)構(gòu),確保每次測試都基於乾淨(jìng)的數(shù)據(jù)庫;2.通過調(diào)用特定種子填充必要數(shù)據(jù),結(jié)合模型工廠生成動態(tài)數(shù)據(jù);3.使用DatabaseTransactionstrait回滾測試更改,但需注意其局限性;4.在無法自動清理時(shí),手動截?cái)啾砘蛑匦虏シN數(shù)據(jù)庫。這些方法根據(jù)測試類型和環(huán)境靈活選用,以保證測試的可靠性和效率。

        選擇API身份驗(yàn)證的Laravel Sanctum和Passport 選擇API身份驗(yàn)證的Laravel Sanctum和Passport Jul 14, 2025 am 02:35 AM

        LaravelSanctum適合簡單、輕量的API認(rèn)證,如SPA或移動應(yīng)用,而Passport適用於需要完整OAuth2功能的場景。 1.Sanctum提供基於令牌的認(rèn)證,適合第一方客戶端;2.Passport支持授權(quán)碼、客戶端憑證等複雜流程,適合第三方開發(fā)者接入;3.Sanctum安裝配置更簡單,維護(hù)成本低;4.Passport功能全面但配置複雜,適合需要精細(xì)權(quán)限控制的平臺。選擇時(shí)應(yīng)根據(jù)項(xiàng)目需求判斷是否需要OAuth2特性。

        在Laravel中實(shí)施數(shù)據(jù)庫交易? 在Laravel中實(shí)施數(shù)據(jù)庫交易? Jul 08, 2025 am 01:02 AM

        Laravel通過內(nèi)置支持簡化了數(shù)據(jù)庫事務(wù)處理。 1.使用DB::transaction()方法可自動提交或回滾操作,確保數(shù)據(jù)完整性;2.支持嵌套事務(wù)並通過保存點(diǎn)實(shí)現(xiàn),但通常建議使用單一事務(wù)包裝以避免複雜性;3.提供手動控制方法如beginTransaction()、commit()和rollBack(),適用於需要更靈活處理的場景;4.最佳實(shí)踐包括保持事務(wù)簡短、僅在必要時(shí)使用、測試失敗情況並記錄回滾信息。合理選擇事務(wù)管理方式有助於提高應(yīng)用可靠性和性能。

        處理Laravel中的HTTP請求和響應(yīng)。 處理Laravel中的HTTP請求和響應(yīng)。 Jul 16, 2025 am 03:21 AM

        在Laravel中處理HTTP請求和響應(yīng)的核心在於掌握請求數(shù)據(jù)獲取、響應(yīng)返回和文件上傳。 1.接收請求數(shù)據(jù)可通過類型提示注入Request實(shí)例並使用input()或魔術(shù)方法獲取字段,結(jié)合validate()或表單請求類進(jìn)行驗(yàn)證;2.返迴響應(yīng)支持字符串、視圖、JSON、帶狀態(tài)碼和頭部的響應(yīng)及重定向操作;3.處理文件上傳時(shí)需使用file()方法並結(jié)合store()存儲文件,上傳前應(yīng)驗(yàn)證文件類型和大小,存儲路徑可保存至數(shù)據(jù)庫。

        See all articles
          <strike id="yu06m"><delect id="yu06m"></delect></strike>