How To Create a Blog using Laravel - (r)

Aug 8, 2023

@yield('content')  Mini-Blog (c) 2023  [email protected]<\/a>">[email protected]<\/a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous">

By using this HTML codes, it is possible to can import Bootstrap version 5.2.3 and Vite to combine the JavaScript as well as CSS assets. The page you create is a header that includes a navbar and a footer, with scripts below. The body contains dynamic content is rendered from different Blade files using the power from @yield('content').

postsdirectory postsdirectory is where you can find the Blade files needed to perform the read and create actions.

  1. Inside within the postsdirectory, create inside the postsdirectory, create a Blade file named index.blade.php and add the below code:
@extends('layouts.app')
 @section('content')
 
 
 Blog list
 
 
 The Blog 1 -  $post 
 
 @endsection

The code is extended beyond that app.blade.php file on the layouts page. When it is rendered in your browser, it displays the blog's content article and also the navigation bar and footer inherited from the app.blade.phpfile in the layouts folder. Between the tag sections, you can pass the contents from the controller to render within the browser after you run the app.

  1. Create the route using the routesdirectory. This allows to load the route automatically of the RouteServiceProvider located in the App/Providers directory. The RouteServiceProvider will be the main class responsible for loading the application's route files.
  2. Inside the routes/web.php file, import PostController using use AppHttpControllersPostController.
  3. Then, set the route by adding Route::resource('posts', PostController::class); to the routes/web.php file.
  4. With the Vite development server running Use PHP artisan server to run the program in your terminal.
  5. With your browser, open http://127.0.0.1:8000/posts to see your new blog post list.

The webpage should appear as these:

The blog application is displayed in the browser
The application for blogging is shown within the browser.

In the next section In the following section, we'll define the controller methods for displaying the entire posts, creating posts, and then storing the post. Add their routes, and then create Blade file in the appropriate sections.

Design blog post Page

Make blog posts by inputting the title, providing a description as well as uploading images. Then, display your posts in a sequential manner.

  1. In the app/Models directory, open in the app/Models directory, open Post.php file.
  2. In the Post class, below it, use HasFactory; code block, insert the protected fillable value ['title', 'description', 'image'];.

This program protects your model's features from being assigned to mass.

  1. In your app/Http/Controllers/PostController.php file, import the Post model using use AppModelsPost;.
  2. Replace the index and create controller methods previously created within the PostController class by using this code:
// Show all posts
 public function index() 
 $posts = Post::orderBy('created_at', 'desc')->get();
 return view('posts.index', ['posts' => $posts]);
 
 
 // Create post
 public function create() 
 return view('posts.create');
 

With the index method that you have just developed in the index method you just created, the PHP application collects all post, puts them in chronological order, and then stores them into the posts variable. The return view shows the posts pass into the index.blade.php file as an instance variable within the views/posts directory. The create method generates the create.blade.php file and puts it into the views/posts directory, if the user tries to make the post.

  1. Create the store controller using the following code (to keep blog entries in the database). Incorporate this code into the PostController class beneath index. Add this code to the index and develop controller methods.
// Store post
 public function store(Request $request) 
 // validations
 $request->validate([
 'title' => 'required',
 'description' => 'required',
 'image' => 'required

The storage method handles client requests regarding the data inside its body. As such, it will take a the request as an argument. After that, you check the fields that are used to create posts and create an instance of a Post instance by using the Post model. Field data that you enter is transferred to the newly created instance and then saved. The site redirects users back to index page, which displays a flash text that says, "Post created successfully."

Create Routes for Your Posts

To add the routes to your web.php file:

  1. Within the routes directory of your project's root directory, you can open web.php. web.php file.
  2. Register the routes for the controller methods, replacing the existing code with this:
names([
 'index' => 'posts.index',
 'create' => 'posts.create',
 'store' => 'posts.store',
 'show' => 'posts.show',
 ]);

The controller utilizes these routes to build, store, and display the data objects you have created.

Make Blade Files

To create the views, return in the class PostController class:

  1. In the resources/views/posts directory, make a Blade file called create.blade.php and add the code below:
@extends('layouts.app')
 @section('content')
 
 Add Post
 
 
 @csrf
 
 @if ($errors->any())
 
 
 @foreach ($errors->all() as $error)
  $error 
 @endforeach
 
 
 @endif
 
 Title
 
 Description
 
 Add Image
 
 
 
 Save
 
 
 
 
 @endsection

In this code, create.blade.php inherits the contents of app.blade.php in the layouts directory using @extends('layouts.app'). This includes a heading, navigation bar and footer. After adding the Add Post text within the h1 tag, you created a form with the post method that contains the route('posts.store') action.

The code enctype="multipart/form-data" allows for image uploads, and csrf protects your form from cross-site attacks. Then, the error messages display invalid field entries, and uses fields attributes to make labels and inputs for the form.

  1. Replace your code inside your index.blade.php file with this code, which will display all the blog posts:
@extends('layouts.app')
 @section('content')
 
 
 Add Post
 Mini post list
 
 
 
 
 @if ($message = Session::get('success'))
 
  $message 
 
 @endif
 @if (count($posts) > 0)
 @foreach ($posts as $post)
 
 
 
 
 
 
 
 $post->title
 
 
 $post->description
 
 
 
 @endforeach
 @else
 No Posts found
 @endif
 
 @endsection

This adds the "Add Post" button. If clicked, it generates a post and passes any information into the body of the page. The if condition determines for data within the database. If it is the condition passes. Otherwise, the screen will display "No Posts found."

Design Your Pages

Now you can use PHP artisan server to publish and show blog posts. Open http://127.0.0.1:8000, and the page should look like this:

The blog application appears in the browser
The application for blogging appears within the browser.

If you add a blog, it will look in the following manner:

The blog application displays a post in the browser
The blog application displays posts within the browser

Deploy Your Laravel Blog on

  1. Make a .htaccess file.
  2. Push the code to a repository.
  3. Set up an online database.
  4. Set up a project on My.
  5. Create and publish your blog.

Make an .htaccess file.

Within the root directory of your project make a new file named .htaccess, and include the following code in it:


 RewriteEngine On
 RewriteRule ^(. *)$ public/$1 [L]
 

This code redirects the application's requests via public/index.php in the deployment.

Send Your Code into the Repository

Make a repository of your project and publish your code. It is possible to use GitHub, GitLab, or Bitbucket to place your code on the web and to upload it to My.

Create the database in Your My Dashboard

Create a database of My:

  1. Click on the "Add Service button, and then select the Database option..
  2. Input the information for your database in the following format. Make sure that, for the installation to succeed, you must leave the Database username as the default value.
Creating a database in My
The creation of a database with My

The details include the Database Name, Display Name, Database type, Version, Database username, Data Center location and the size. This example uses MariaDB as the database and the dimension can be described as Db3 (1CPU / 4GB RAM/10GB Disk Space, 65 USD per month). It is possible to select the type of database and size to meet your particular requirements.

  1. Click Continue.
  2. Verify your monthly costs as well as the payment method. Then select Create database.

Set Up the Project to My

In order to deploy your application My:

  1. Click the Dashboard panel.
  2. Simply click Add Service and choose the Application like the following:
My dashboard when adding application service
My dashboard after adding the applications service

My will take users to Apply Application page.

  1. Under the Select branch card section, click your repository on GitHub, and then click the Add deployment to commit checkbox.
  2. In the Basic information in the basic details section, type in your application name and select the location of your data center for the application.
  3. As Laravel requires an app-specific key during deployment, in the environment variables card, include an app key as Key 1. The key can be used as the APP_KEY defined in your locally stored .env file or make use of an online key generator for Laravel to get one.
  4. Click Continue.
  5. Pick the appropriate build resource (CPU and RAM) for your application. This demonstration employs the typical build machine (1CPU / 4 GB RAM) + 0.02USD per minute.
  6. Make sure to leave the Image of the container to be set up in place by pressing the radio button.
  7. Click to continue.
  8. In the Setting up your process webpage, you can modify the pod size as well as the type of instance, by choosing these boxes. This example uses the defaults.
  9. Click to Continue.
  10. Then, press then the "Confirm Payment Method" button to initiate your application's deployment. Clicking this also directs you to the information about your deployment page, where you will be able to see your progress on your deployment.

Develop and Launch Your Application

Once the application and database are hosting, connect the database to your application, and then build it the application to be deployed.

To connect to your database, use the external connections of your hosted database. In the Infotab of your hosted database there are External connections which are as follows:

External connections for your hosted database
External connections to connect your database hosted on the internet
  1. In the app's Settingspage, navigate towards the Environment variable card.
  2. Click Add an environment variable to add the external connections to your database hosted by the value that corresponds to it. Use the same variables found included in the .env file.
The environment variables for your hosted database
The environment variables for your hosted database

This picture is helpful to consider marking env variables you edited manually in order to distinguish them from other ones.

The app_urlis the URL for the application you host, and DB_CONNECTION is mysql.

  1. Visit your app's settings page.
  2. Within the Buildpackcard, add PHP as well as Node.js to build packs. Since it is a PHP application, it is necessary to install the PHP build pack after Node.js.
  3. Click Install now to build your application.

Then, you can add a procedure to migrate your database.

  1. Visit the Processestab of your host application's page.
  2. Choose the the Create process on the process card.
  3. Input Migration as the name, Background worker as the kind and PHP artisan migrate to initiate the command. You can leave the pod dimensions and the number of instances using the defaults.
  4. Choose Continueto begin the application. This will trigger a brand new build and redeploys the application.
  5. In your domainstab of your application, click the link for your application. You can see that it's currently running.
  6. Note that the blog application deployed to My displays no blog posts. Create a new post by typing the title of your post, adding a description, selecting an image.

Summary

Laravel lets you make a basic blog in a short time. Its rapid page loading and robust controller design and a dependable security system make improving an application's performance easy. In addition, My lets you release and deliver your online applications quickly and effectively. My's pricing structure is based upon usage which eliminates any hidden costs.

Marcia Ramos

I'm the Editororial Team Leader at . I'm a fan of open source and am a huge fan of coding. Over the past seven years of technical writing and editing for the tech industry, enjoy working with colleagues to create short and precise pieces of content and improve processes.