<tr id="ixdut"><span id="ixdut"></span></tr>
    1. \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 requires 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国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

          Table of Contents
          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
          Home PHP Framework Laravel How to build a blog with Laravel from scratch?

          How to build a blog with Laravel from scratch?

          Aug 02, 2025 am 10:16 AM

          Install and create Laravel project, use the composer create-project command to initialize the blog project and start the development server; 2. Configure the database, set MySQL connection information in the .env file and create a blog database; 3. Create Post model and migration file, define title, content, slug, is_published and other fields and perform migration; 4. Generate PostController resource controller, query published articles in the index method and display them on a page; 5. Use the Blade template engine to create layout and view files, including article lists and details pages; 6. Register resource routes in web.php, and only index and show methods are open for public access; 7. Implement the show method to find and display a single article through slug; 8. Optionally install Laravel Breeze implements authentication, creates an administrator-specific route and controller to process article additions, deletions, modifications and searches; 9. Further optimize functions, such as adding Markdown parsing, image upload, classification tags, SEO support, comment system and search functions; in the end you will get a Laravel blog system with basic functions, MVC architecture, and extensible, ending with complete sentences.

          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 requires 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.

          The above is the detailed content of How to build a blog with Laravel from scratch?. 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

          Undress AI Tool

          Undress AI Tool

          Undress images for free

          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.

          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)

          Creating Custom Validation Rules in a Laravel Project Creating Custom Validation Rules in a Laravel Project Jul 04, 2025 am 01:03 AM

          There are three ways to add custom validation rules in Laravel: using closures, Rule classes, and form requests. 1. Use closures to be suitable for lightweight verification, such as preventing the user name "admin"; 2. Create Rule classes (such as ValidUsernameRule) to make complex logic clearer and maintainable; 3. Integrate multiple rules in form requests and centrally manage verification logic. At the same time, you can set prompts through custom messages methods or incoming error message arrays to improve flexibility and maintainability.

          Working with pivot tables in Laravel Many-to-Many relationships Working with pivot tables in Laravel Many-to-Many relationships Jul 07, 2025 am 01:06 AM

          ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

          Sending different types of notifications with Laravel Sending different types of notifications with Laravel Jul 06, 2025 am 12:52 AM

          Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

          Understanding Dependency Injection in Laravel? Understanding Dependency Injection in Laravel? Jul 05, 2025 am 02:01 AM

          Dependency injection automatically handles class dependencies through service containers in Laravel without manual new objects. Its core is constructor injection and method injection, such as automatically passing in the Request instance in the controller. Laravel parses dependencies through type prompts and recursively creates the required objects. The binding interface and implementation can be used by the service provider to use the bind method, or singleton to bind a singleton. When using it, you need to ensure type prompts, avoid constructor complications, use context bindings with caution, and understand automatic parsing rules. Mastering these can improve code flexibility and maintenance.

          Strategies for optimizing Laravel application performance Strategies for optimizing Laravel application performance Jul 09, 2025 am 03:00 AM

          Laravel performance optimization can improve application efficiency through four core directions. 1. Use the cache mechanism to reduce duplicate queries, store infrequently changing data through Cache::remember() and other methods to reduce database access frequency; 2. Optimize database from the model to query statements, avoid N 1 queries, specifying field queries, adding indexes, paging processing and reading and writing separation, and reduce bottlenecks; 3. Use time-consuming operations such as email sending and file exporting to queue asynchronous processing, use Supervisor to manage workers and set up retry mechanisms; 4. Use middleware and service providers reasonably to avoid complex logic and unnecessary initialization code, and delay loading of services to improve startup efficiency.

          Managing database state for testing in Laravel Managing database state for testing in Laravel Jul 13, 2025 am 03:08 AM

          Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

          Choosing between Laravel Sanctum and Passport for API authentication Choosing between Laravel Sanctum and Passport for API authentication Jul 14, 2025 am 02:35 AM

          LaravelSanctum is suitable for simple, lightweight API certifications such as SPA or mobile applications, while Passport is suitable for scenarios where full OAuth2 functionality is required. 1. Sanctum provides token-based authentication, suitable for first-party clients; 2. Passport supports complex processes such as authorization codes and client credentials, suitable for third-party developers to access; 3. Sanctum installation and configuration are simpler and maintenance costs are low; 4. Passport functions are comprehensive but configuration is complex, suitable for platforms that require fine permission control. When selecting, you should determine whether the OAuth2 feature is required based on the project requirements.

          Implementing Database Transactions in Laravel? Implementing Database Transactions in Laravel? Jul 08, 2025 am 01:02 AM

          Laravel simplifies database transaction processing with built-in support. 1. Use the DB::transaction() method to automatically commit or rollback operations to ensure data integrity; 2. Support nested transactions and implement them through savepoints, but it is usually recommended to use a single transaction wrapper to avoid complexity; 3. Provide manual control methods such as beginTransaction(), commit() and rollBack(), suitable for scenarios that require more flexible processing; 4. Best practices include keeping transactions short, only using them when necessary, testing failures, and recording rollback information. Rationally choosing transaction management methods can help improve application reliability and performance.

          See all articles
        • <ruby id="g3b62"></ruby>