Uncategorized

Building Your First Laravel Application (Blog Application)

Laravel is a free, open-source PHP framework for web artisans, based on Symfony, that helps build web applications following the MVC (Model View Controller) design pattern.

There are two ways to build a laravel application is using the laravel installer. The other requires the Laravel package and for us to use a composer and a create-project command.

Reading: How to create a blog in laravel 5

In this tutorial we will use the latter.

Step-by-step -Guide on how to create your first Laravel (blog) application

Following is some information about the Laravel framework:

  • Framework: Laravel
  • Author: Taylor Otwell
  • Initial publication date: June 2011
  • Current version : 8 (September 8, 2020)
  • Stable Release: 8.11.2 (October 28, 2020)

What is Laravel?

h3>

The short version is that Laravel is a PHP MVC framework. The long version would be, Laravel is a free and open-source PHP framework for web artisans, based on Symfony.

It helps in creating web applications following the MVC (Model View Controller) design pattern ). To help us understand Laravel better, we’re going to build a simple blog application from scratch using Laravel.

Requirements: In order to build a Laravel application, you need to have some tools installed on your computer.

These tools include:

  • PHP >= 7.3.
  • Database (MySql).
  • A localhost web server – In our Case we have I use WAMP (for Windows), LAMP (for Linux) or MAMP (for MacOs). This localhost web server comes installed with the latest PHP and MySQL database, so you don’t have to install them manually. To install either MAMP, LAMP, or WAMP, go to http://ampps.com/downloads and select your platform’s software.
  • Composer – This is dependency management software for PHP. To install Composer, visit https://getcomposer.org/ and download it there for your platform.
  • Node.js – This is a free and open-source JavaScript runtime environment that uses JavaScript outside of the browser executes. We won’t be writing any Node.js code, but it will be used by Laravel behind the scenes to streamline our development.
  • Code Editor – A code editor is required. We recommend using Visual Studio Code: it’s free.
  • A browser – Google Chrome, Edge, Safari or Mozilla Firefox will do just fine.
  • Background knowledge of PHP programming language.

Now that our machine setup is complete, it’s time to start developing.

Create a new Laravel application

How As we mentioned earlier, there are two ways to create a Laravel application; one uses the Laravel installer and the other uses the Laravel package installation; and use a composer and create-project command.

In this tutorial we use the latter:

  • Open your console and cd to www directory in Your MAMP, LAMP, or WAMP installation directory.

  • Type the following command:

It will enter a Directory named my -blog and load all primary Laravel files there.

Configuring our Laravel application

After installing our Laravel application, we need to configure our database to make it work.

  • Go to http://localhost/phpmyadmin/
  • Create a new database by clicking New (shown in red below)

new database

  • Name it my_blog and click Create

Now that we have a database, we can proceed to create the app Set up the application to work with the database.

  • Open your file explorer and navigate to the my-blog folder
  • O Write the .env file in your code editor
  • Change the following in the file:-

APP_NAME key to the name of your blog, e.g. “My Blog”

DB_DATABASE key to database name, e.g. B. my_blog

The final file should look like this:

Once everything is configured, it’s time to run our app and see how it looks.

To run the application, type the following command:

It will launch the application and give you a URL, http://127.0.0.1:8000, open the URL in your browser and see Application (see below).

 Homepage

Understanding the Laravel application file structure

Before we start coding, let’s understand the file structure of a Laravel application.

For example , most of you may not understand why we changed the .env file.

Below is the Laravel app file structure:

files

app folder – This contains all the logic in our application, this includes the models, controllers, service providers, etc.

app files

As a beginner, you will spend most of your time in the Models and Controllers folders, these two will be we will discuss in detail.

  • Models folder – This is where your app’s business logic is stored, a model is a representation of a real-world object.

Models are created with the PHP craft command make:model will generate and follow a case-sensitive title convention, for example for a blog post model we could name BlogPost.php .

Note: Laravel comes with a User.php model that defines user details:

  • Http/Controllers folder – This contains all your application’s controller files.

A controller creates a connection between your models and your views When a user submits a new blog post form, the data comes into the Controller where it is sanitized and pass the n to the model to be stored in the database, then the controller sends feedback back to the view that the blog post was created.

Controller generated with the PHP Artisan make:controller command, and follow a singular letter phrasing convention with the suffixed word controller. For our blog post controller, let’s call it BlogPostController.php

A controller has 7 signature methods that allow crud operations:

  1. index() – to get all resources, e.g . all available blog posts.
  2. show() – to retrieve a single resource, e.g. a single blog post, let’s say post 5.
  3. create() – shows the form to use to create a resource (not available for API controllers).
  4. store() – to store the resource in the database, e.g. Save blog post.
  5. index() – to display the resource edit form (not available for API controllers).
  6. update() – to add the edited resource to the database take over.
  7. destroy() – to delete a resource from the database.

Now back to the file structure of our Laravel app:

  • Http/ Middleware folder – This contains all middleware, middleware is code that needs to be executed before the request gets to the controller e.g. Authenticating a user before granting access.
  • Exceptions folder – This contains all the exception handling in your app, you can also add custom exceptions here.
  • Console folder – This one contains all the PHP artisan commands (PHP Artisan is the command line tool that comes with Laravel to help us develop our application faster). These commands are used to build application files and also perform some actions like starting a development server. An example of an Artisan command is the one we ran at the beginning after installing Laravel (php artisan serve).
  • Providers folder – This contains all the service providers in your app, a service provider in Laravel is one Group of code that performs specific tasks in the app as needed. For example, a billing service provider is designed to allow multiple payment platforms, but you just have to call the service provider and they dynamically provide a payment platform instead of specifying a platform in the controller.

NOTE: Service Providers are a difficult concept to understand for beginners, but once you get used to them, they really come in handy.

  • Bootstrap Folder – This contains the app file, which boots the framework by initializing it (setting up the path and environment), it also contains the cache folder that contains the files generated by the framework for optimizing the app.

NOTE: Bootstrap folder has nothing to do with Bootstrap CSS Framework.

  • config folder – This contains all configuration files of the app. To get a specific configuration, Laravel provides a helper method for that.

For example:

Getting the app name we would use:

In this example, app is the configuration file we’re looking in, name is the key, while ‘Default Name’ is the name to use if the key or file doesn’t exist.

  • database folder – This folder contains database migrations, factories, and seeds. Migrations are database table definitions like columns and their data types, necessary key definitions, etc.

Factories are blueprints used to create sample data for the database, while Seeds are the sample data for our database. They are actually commands that will trigger the creation of sample data when executed.

You can also store the SQLite database files here.

Note: Laravel comes with users_table comes migration and UserFactory.php factory out of the box that will help create user tables and define sample data for our user table.

  • Public Folder – This folder contains the Index file, which is the entry point of the app, it encounters this file after the request and then it is directed to the required route.We will learn more about routes later. You can also store public assets like public images, css, and js here.

  • resources folder – This folder contains our app’s compatible source files, including Views, Sass, and Raw JavaScript files (mainly Node.js or from JS Frameworks). Views are created using HTML with a mix of a Laravel templating engine called Blade, we’ll learn more about that later.

  • routes folder – This folder contains all the route files to our app these route files include web.php, api.php, channels.php, console.php. Each file contains multiple user-defined routes. A route is simply a web address that points to a specific function either in the route file or in the controller.

  • Storage folder – This contains all private files, such as B. Customer profile pictures. From here a dynamic link to the public can be created. All app logs are also stored here.

  • Tests folder – This is where your app tests are stored.

  • Vendor folder – This is where all third-party packages brought by Composer are stored.

  • .env file – This file contains the environment variables, these variables are brought in by configuration files using the env helper method.

NOTE: Avoid using the env() helper method in your code, only use it in configuration files. This is because during deployment if you cache the environment (you will learn how) all the environment variables are loaded into the configuration and the .env file is deleted.

Understanding a Request Lifecycle

Laravel, like any other server-side platform, works on a request-response model; H. the user sends a request and gets a response in return.

Assume the user wants to read blog post 5, for example, he sends a get request to retrieve that post; The request route (URL) would be as follows: http://my-blog.test/blog/5

First the request goes to the public/index.php file, the app registers a new request and the Check the routes/web.php file to see if the route is registered. Otherwise, a 404 error is thrown. Otherwise, the app will check if any middleware needs to be executed before forwarding the request to the controller method assigned to the route.

Once all middleware has been executed, the request will be forwarded to the required method, in this case the show() method is in BlogPostController.php.

Inside the controller, the request is executed, i. H. the post is retrieved from the database, then the BlogPost object is passed to the view and the user gets the view as a response. The view is then rendered in the browser.

This completes the request process.

Let’s code!

Now that we better understand how a request works works and what different files and folders of a Laravel application are needed, now we will start developing our blog.

Create BlogPost Model

First we will create BlogPost Model To create a model, we’ll use the php artisan make:model command followed by the name of the model.

This will create a file called BlogPost.php in our App/Models folder, and ladies Gentlemen, that’s all you need to do to create a model.

Perform blog_posts table migration and migrate database

Now let’s create a migration for the model.

To create a migration, we use the php artisan make:migration command followed by the words action_table_name_t able.

In our case:

TIP: Always make sure your table name is plural with your model name in lower case.

This will create a file in the database/migrations folder. The file will have the current timestamp before the name you specified in the command: 2020_11_17_163409_create_blog_posts_table.php.

See also: Lets build data apps to transform your business processes

Once you have created the migration, we need to fill it with the fields we found inside the Schema:: create method , our final file will look like this:

The three fields I marked with a block comment are all I added, the rest are prefilled.

$table->id(); – Creates an ID field which is also the primary key in our table.

$table->timestamps(); – Creates two TIMESTAMP fields (created_at & updated_at).

Once we’ve created the migration, all we have to do is migrate to create the tables in our database. Run the migrate command (below) to migrate.

This will create tables in the database for us:

Create a factory and seed for our blog_post table

Now that we’ve created our table, it’s time to populate it with data. The user factory (UserFactory.php) already exists and now we are going to create a factory for our blog post.

To create a factory, we use the make:factory command followed by the name of the class that we also use add the -m flag followed by the model name to assign a factory to this model.

A file named BlogPostFactory.php will appear in the database/factorys folder.

Inside the definition method, we will edit the return array to define our blog post data, we will insert:

Now that we have created our factory, is it’s time to create a seeder to seed our database. We will do this with PHP Artisan Tinker. Tinker is a command line tool that comes with Laravel to allow data manipulation without changing the code during development, it’s a good tool to do seeding and test relationships.

To open Tinker , type:

This will launch a command line that looks like this:

Tinker

Start typing your code and press Enter to run it.

To seed type:

This will generate create 10 blog posts and store them in the database and also generate 10 users, each user will own one blog post.

Create Controller

Controllers help us perform resource manipulation actions like CRUD Ops. To create a controller, we use the make:controller command followed by the controller name. To associate the controller with a model, use the -m flag followed by the model name.

The naming convention for controllers in Laravel is ModelName followed by the controller name. For the BlogPost.php model, the controller is BlogPostController.php.

This creates a file named BlogPostController.php in the app/Http/Controllers folder.

The file looks like this:

The file will be created using all available resource manipulation methods and the BlogPost model will be included in the file by default.

Working with Routes

Now that we have After you Once we’ve created our controller, we’re going to target one of the methods, say index(), that use a route.

All web routes are stored in the routes/web.php file.

Open the file and you will see the default (root) route to our application. Immediately below the root route, we’ll create the blog route, which will open the blog and show all available posts.

To show that we’re targeting the index method within the BlogPostController.php class.

It will be a get route since we are retrieving data.

Our routes/web.php file will look like this:

If you visit this route now, an empty screen displayed . In the next sections we will create more routes and implement the available methods.

Implementing the Controller Methods

1. Show all blog posts using index() method

If we navigate to http://127.0.0.1:8000/blog, you will see a JSON dump of the available posts (10 posts).

So:

Blog Dump

I installed a Chrome extension called JSON Formatter to help me format the JSON dump, it’s a free plugin, you don’t need to install it if you don’t need it.

2. Viewing a blog post

Create a route to view 1 post.

The route is:

Here we introduced {blogPost}, this is referred to as a denotes placeholder. This means that {blogPost} will be replaced with whatever is typed after blog/ and that value will be stored in the variable named $blogPost.

In the Show method, we have:

When we visit http://127.0.0.1:8000/blog/5, it will automatically fetch the BlogPost with ID 5 and store it in $blogPost as an instance of the BlogPost model.

This will called route model binding in Laravel. You specify a route with a wildcard that is replaced with the value specified in the URL, then Laravel uses that value to try to find the record associated with that value, specifically the record with that ID.

If yes is not found, you will get a 404 error.

This is the response you will see in your browser:

Blog Post

WARNING: The key we use for Using the wildcard must be the same name as the variable name in the show method for model route binding to occur. For example, if the route placeholder is {blogPost}, the variable name in the show(BlogPost $blogPost) method of the public function must be $blogPost.

Working with other methods

So far we’ve only worked with get routes. The create() and edit() methods are intended to display the create and edit forms respectfully.

The store() method will be a post-http verb since we are using the create-BlogPost form to save the data, the update() method needs a put or patch verb to update data, and the Destroy() method needs a delete verb to delete the post.

TIP: HTTP verbs are also mentioned. As methods or actions, they are typically used to define the action to be performed on the server.

Z. A POST verb/action/method is used to send data to the server, a GET method is used to get data from the server, a PATCH/PUT method is used to update data, and a DELETE method is used to delete data from server.

There are other verbs, but you will rarely use them even in a professional development environment.

We will implement these after learning how to create the UI , for now we can create their routes.

Working with views and designing the user interface

Laravel uses a templating engine called Blade, which is injected into HTML and finally evaluated as HTML.

First we will learn the Blade syntax, which will help us get started.

We will compare the syntax we use on Blade with that of regular PHP interior views:

Blade Syntax

TIP: The PHP syntax is still accepted in the Laravel views, but as you’ve seen, it’s clumsy. Using Blade syntax is better.

Blade has more terms and directives that we need to understand:

  • View – an HTML file in Laravel , such as user interface.
  • Layout – This is the basic framework of the app, it defines the main elements like headers and footers for consistency and also contains the most important scripts and styles.
  • Component – Components are reusable views, they can be a button for example.

Blade directives and what they mean:

Blade Directives

These are the ones we are going to use now, you can always read more about them learn Laravel documentation [here}(https://laravel.com/docs/8.x/).

Knowing this, we are now ready to design our Laravel app.

1. Design our app layout

Create in the folder resource/views folder and name it layouts. Then create a file in the folder and name it app.blade.php.

Below is the final code of what the file will look like:

With this we have created our layout , it’s just an HTML page with Google font and Bootstrap in it.

In the title { { config(‘app.name’) }} – Is a helper method for Laravel config access to access our Access the app name that will be displayed as the title of our page.

In the body @yield(‘content ) – is a blade directive used to bring content from child views into the layout.

2. Welcome Page Design

This is the page we saw when we created our first application. We’re going to refactor it to show the welcome page. We will extend our layout using the @extend directive. It is located in the resources/views folder with the name welcome.blade.php.

The final code on the page looks like this:

This is what it should look like in the browser. The View Blog button displays the blog page that we will be designing next.

See also: How to Set Up an Email Account that Uses Your Domain Name

Home

3. Designing the blog page

In our current blog page, we return raw json data to the user.

In this section, we return a view to the user to do this do, We can use a method that Laravel gives. Instead of return $posts we say return view(‘view.name’, [$data]); so let’s change the code in BlogPostController.php inside the index() method to return a view instead of a JSON file.

Before we change the code, first go to the resources/views folder and create a folder called blog and in that folder create a view file called index.blade.php, this will be our index method view or the view to show all blog posts.

Then change the code in your BlogPostController. php in index() look like this:

This gives us access to a variable called $posts in our view, which is an object that contains multiple blog posts.

Now, let’s design our blog posts page.

The code looks like this:

On this page, the blade iterates through the posts (if it’s not null) and spits out a link from each post and with a post title as link text.

The post ID is appended to the link.

  • id }}”>{{ ucfirst($post->title) }}
    • ./blog/{{ $post-> id }} – A blog post -ID is appended to the URLs, so the formed example URL for post 5 is http://127.0.0.1:8000/blog/5
    • {{ ucfirst($post->title) }} – Post title formatted with every first letter in upper case.
    • The Add Post button helps us to create a new post.

    The page looks like this in the browser:

    blog page

    4. Designing the BlogPost Page (http://127.0.0.1:8000/blog/5)

    In our current blog post page, we’re still returning raw JSON data to the user in this section we will return a view to the user.

    We will change the code in BlogPostController.php in the show() method to return a view instead of json data.

    Before we change the code, we must first go to the resources/views/blog folder to create a view file called show.blade.php, this will be our show method view or view , which should be displayed in a specific blog post.

    Then change the code in your BlogPostController.php in the show() method to look like this:

    So we have Accessing a variable called $post in our view, which is the object that contains the blog post we want to display.

    Now let’s design our blog post page.

    The code looks like this:

    {!! $post->body !!} – We used this directive to ensure that HTML in the body is displayed as bold text.

    id }}/edit” class=”btn btn-outline-primary”>Edit Post – Click to edit the post.

    This form is used to delete the post . The @method(‘DELETE’) directive creates a field that overrides the default post method with the DELETE method. The same goes for the @csrf directive.

    As shown below:

    csrf and method expands

    The back button takes us back to the blog page.

    This is how our page works now in the browser.

    blog post page

    5. Create New Post Page

    We have already created a route for this page http://127.0.0.1:8000/blog/create/post.

    We will first change the code in the File BlogPostController.php in the create() method to return the view.

    Before we change the code, first go to the resources/views/blog folder and create a view file called create.blade. php, this will be our create method view or the view to display a form needed to create a blog post.

    The create() method code is as follows:

    Now let’s design our view.

    The code looks like this:

    This form will send a POST request to this route http://127.0.0.1:8000/blog /create/post.

    The @csrf directive is expanded in the browser to give us the token field in the form.

    The page looks like this in our browser.

    New Post Page

    6. Accepting and saving the submitted post

    Inside our BlogPostController.php in the store() method we implement the code to save the post in the database and redirect the user to the created post.

    The code looks like this:

    Here we use the static method Model::create(), which accepts an associative array with keys as table field and value as data to be inserted into the table.

    Here we assign our contribution to user_id 1. You can learn more about Laravel authentication later to learn how to associate a post with the logged in user, Laravel has many authentication techniques. You can see them here.

    The return value is a redirect that redirects to our single post route with the post’s id.

    Well, before we’re done, we have one more thing to do slightly modify our model (BlogPost.php) to show the fields that are fillable to protect them from unwanted entries.

    The modified model looks like this:

    So that are we added post.

    7. Editing a post

    We have already created a route for this page http://127.0.0.1:8000/blog/{blogPost}/edit.

    We will change the code first in the BlogPostController.php file in the edit() method to return the view.

    Before we change the code, first go to the resources/views/blog folder and create a view file called edit. blade.php, this is our edit method view or the view to display a blog post edit form.

    Then change the code in your BlogPostController.php file in the edit() method like this that it looks like this:

    This gives us access to a variable called $post in our view, which is the object that contains the blog post we want to edit.

    The view looks like this:

    This shows a pre-filled form.

    @method(‘PUT’) – This expands to an input field that is used to enter the standard POST verb to overwrite as we saw with the @method (‘DELETE’).

    8. Updating the Post

    In our BlogPostController.php file in our `update() method we implement the code to save the post to the database and then redirect the user to the edited post.

    The code looks like this:

    Here we use the $modelInstance->update() method, which accepts an associative array with keys of the table field and the value is the data we have update.

    That’s all we need to update our post.

    9. Deleting a post

    In our BlogPostController.php file in our Destroy() method we implement the code to save the post in the database and then redirect the user to the edited post.

    The code looks like this:

    Here we use the $modelInstance->delete() method, which deletes the post from the database.

    That’s it everything needed to delete a post.

    Conclusion

    With this article we learned how to create a Laravel project from scratch, we have the example of a functional blog.

    This was a beginner’s course, so I didn’t want to overwhelm you with a lot of information. But at least you’ve learned all the core Laravel concepts, starting with models, controllers, views, routes, migrations, and factories.

    You’ve learned the key actions required for each application, such as create, update, Read and delete data. Also known as CRUD.

    Knowing this, you can now enhance the application to add more functionality.

    For full Laravel documentation, click here.

    Peer review contributions by: Michael Barasa

    See also: Insights

    .

    See also  How to Create a Distribution List in Outlook

    Related Articles

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Back to top button