Laravel simple user CRUD app for beginners

This is a simple tutorial where you can learn how to create a Laravel application using Laravel, PHP, and MySQL. Learn how to let users register, log in, log out, create blog posts, query for only blog posts they’ve authored, and more. My motivation is to learn more about Laravel, watch tutorials, and recreate as much code on my own as I can. I found one great tutorial for beginners on YouTube and made some comments about it. You will write code and delete code on the go to learn as much as possible. Here is the original YouTube video, source code, and below you will find my notes for this video. I hope it will help you better understand how Laravel works if you don’t have time to watch the entire video.

Source code: https://github.com/LearnWebCode/youtube-laravel-demo

Create new Laravel project

  1. Navigate to the Laravel project directory:
    C:\wamp64\www\BackEndDeveloper>cd laravel
  2. Create a new Laravel project in the current directory using Composer:

    This command fetches the Laravel framework and installs it in the current directory (denoted by .).

  3. After creating the project, go back to the main directory and start the Laravel development server:

    This command starts the development server, and you should be able to access your Laravel application at the provided URL (usually http://127.0.0.1:8000) in your web browser.

Make sure WampServer is running and configured correctly for PHP and other dependencies required by Laravel. If you encounter any issues, check the error messages or logs for more information.

Open Laravel project in code editor (VSC recomendded)

  1. Creating a New View:
    • Open your terminal or command prompt.
    • Navigate to your Laravel project directory.
    • Use the make:view Artisan command to create a new Blade view. For example:

    This will create a new Blade view file named your_view_name.blade.php in the resources/views directory.

  2. View Location:
    • By default, the resources/views directory is where Laravel stores its Blade views. The new view file you created will be located in this directory.
  3. Editing the View:
    • Open the newly created Blade view file in a text editor of your choice.
    • Customize the content of the view according to your needs.

Create home.blade.php view

Rendering the view home.blade.php

In Laravel, routes are typically defined in the routes directory of your project. The main file where you can define routes is: web.php. This file is used for defining routes that are associated with web-based interfaces. It includes routes for handling HTTP requests like GET, POST, etc. The routes defined in web.php are usually associated with web pages and user interactions.

When we click on the ‘Register’ button in our home.blade.php view, we must include the @csrf token for POST requests; otherwise, we may encounter an error.

CSRF token

When you have a form in your home.blade.php view, especially for actions like user registration, it’s important to include the CSRF token to protect against CSRF attacks. CSRF tokens help ensure that the form is submitted by the same application that renders the form and not by a malicious third party.

Now, when we click the ‘Register’ button, the return function displays the text ‘thank you’.

We need to move functions from the web routes to the controller, located at app/Http/Controllers. Let’s name it UserController. To do this, we should create the UserController.php file.

How to make UserController

UserController.php first function

Now, let’s go to web.php, remove the function, and add the controller function. Additionally, we need to import the UserController class.

Adding post route with class function in web.php

It’s convenient to have a PHP extension for Visual Studio Code called ‘PHP Namespace Resolver for importing classes.

UserController.php validate input fields

We must name the input fields in home.blade.php so they can get forwarded to $request.

Let’s add some more validation rules for input fields.

Laravel .env file

In the .env file, configure the database connection settings to store this data in it. After configuring the database settings, we need to perform a migration.

The .env file in Laravel is used for environment-specific configuration, allowing you to define various settings for your application. In the context provided, it suggests configuring the database connection details within the .env file.

Database Connection Configuration:

Laravel uses the .env file to store sensitive information, such as database connection details (e.g., database name, username, password).

Laravel migrations

  • Once the database connection is configured, Laravel migrations are used to create database tables or modify existing ones.
  • To run migrations, you use the Artisan command: php artisan migrate.
  • This command reads migration files in the database/migrations directory and applies the changes to the database schema.
  • Example migration file (database/migrations/2022_01_01_create_users_table.php):

Laravel artisan command line migrate

After configuring the database settings, we need to perform a migration:

If the migration encounters issues, we can execute a rollback:

If that doesn’t work, manually delete the tables created in the new database by the migration (e.g., tables like ‘users’), and then run the migration again.

drop_migrations_tables_laravel

For Windows users, it’s advisable to check the database configuration, specifically the engine, located in config/database.php. Ensure that the engine is set to 'InnoDB':

Then, run the migration once more:

Laravel models

To create a record in the database after validation in the register function, we want to instantiate a new instance of the User model.

A MODEL IS A MENTAL MAPPING OF DATA FOR AN ITEM OR ENTITY.

So, we will have a model for blog posts, a model for registration, and a model for post comments.

A MODEL maps data structures and relationships for a specific portion of data.

LARAVEL ALREADY PROVIDES A USER MODEL FOR US!

Usercontroller.php hashing password

Let’s hash the user’s password

This ensures that the user’s password is hashed before being stored in the database. The bcrypt function is used for secure password hashing in Laravel.

Never store a password in plain text in the database!!! Let’s also add the User namespace to the controller.

Register user and look in database

Try your program, and register a user and look into the database to see if the user is registered and his password hashed.

As you can see here, the password is hashed.

Usercontroller.php login and logout function – sessions and cookies

Rules and constraints in data validation

Let’s add a rule where username and email must be unique. That laravel can look into the database, that the same user and email do not exist. In the users table, the field user and email must be unique.

To check that we are really logged in, go to the home.blade.php template.

Alright, let’s create a route to navigate beyond the current page. Additionally, we require a log out button within home.blade.php, placed inside a form and accompanied by the CSRF token, of course.

Now, let’s define the route in web.php.

Log Out

Now, we need to define the logout function in UserController.php.

Let us try accessing 127.0.0.1:8000 in our web browser to see if we have all the elements now and that everything is working properly.

Log Out

Log in

Now that we have the option for registration and login through the registration function, we want to add the option for login without registration. Below the registration form, let’s create a login form in home.blade.php.

To avoid having the same names for input fields in the same view (home.blade.php), we’ve changed them to ‘loginname’ and ‘loginpassword’. We also modified the form action to ‘/login’. This login form will submit data to that URL ‘/login’. Let’s check now how this looks.

Now, we need to add the login route in web.php.

After adding the login route, of course, we need to create the login function in UserController.php.

Login function in UserController.php

In Laravel, there’s a fantastic way to create database tables. There’s a folder called migrations. Open the Command Prompt (Cmd) – Laravel can somewhat anticipate our intentions.

C:\wamp64\www\BackEndDeveloper\laravellwc> php artisan make:migration create_posts_table INFO Migration [C:\wamp64\www\BackEndDeveloper\LaravelLWC\database\migrations/2024_01_19_121142_create_posts_table.php] created successfully.

A new file has been created in the /database/migrations/ directory: 2024_01_19_121142_create_posts_table.php.

Let us add some fields in the table that we need.

Database Schema builder

If you want to add fields to the migration file, you can open the newly created migration file, which is likely named 2024_01_19_121142_create_posts_table.php in the database/migrations directory.

Open the file and you will see a up method. Add the fields you need inside the up method using the Schema Builder.

Running php artisan migrate in Laravel executes all pending migrations that haven’t been run yet. In your case, it successfully ran the migration for creating the posts table. The output indicates that the migration 2024_01_19_122408_create_posts_table was executed successfully.

You can now find the posts table in your MySQL database with the specified fields. If you encounter any issues or need further assistance, feel free to ask!

Create post view in home.blade.php

Let’s add functionality to the view home.blade.php

Let’s create the PostController for handling data. C:\wamp64\www\BackEndDeveloper\laravellwc> php artisan make:controller PostController

INFO Controller [C:\wamp64\www\BackEndDeveloper\LaravelLWC\app\Http\Controllers\PostController.php] created successfully. Open PostController.php – it is located in app/http/controllers/PostController.php. A quick way to find new files is to use CMD for Mac or CTRL + P for Windows.

PostController.php

Let’s create a new function called createPost.

Make model Post.php

We don’t have a model for ‘Post’, ‘post’ is underlined as an error in VSC editor. We need to create a model for posts, i.e., the ‘Post’ model. Laravel had the ‘User’ model, but there isn’t one for ‘Post’, so we need to create it ourselves. We create the model using the command in the CMD. Since the table in the database is named ‘posts’ in lowercase plural form, the model should be named in singular Uppercase form (first letter capitalized). This is the recommendation, and that’s how Laravel works.

Let’s go to Post.php.

Web.php for posts

Let’s go to web.php, and let’s display all the posts for all users first…

To display posts, we need to create a view – home.blade.php

View home.blade.php for All posts

Now we see all posts from all users. But what if we want only the posts of the logged-in user?

We will change this to not display all posts.

Let’s look at the first case, which does not use a relationship.

Web.php – posts without relationship use

Although this works, the whole reason for setting up relationships is missed because in this line of code, we start from the perspective of a blog post. Let’s instead approach it from the perspective of the user model.

Web.php display user posts using User model

In the provided code, auth()->check() is used to check if a user is authenticated (we are calling an instance of a user model). If the user is authenticated (auth()->check() returns true), it fetches the cool posts belonging to that authenticated user’s instance of the user model. If the user is not authenticated, it retrieves all posts.

Also, note that calling auth()->user() without using the result won’t have any effect. If you intend to use the authenticated user in your logic, you might want to store it in a variable:

or like this

Edit and delete posts

Let’s now enable editing and deleting posts.

Navigate to home.blade.php.

Below each post, let’s add edit and delete links.

The edit link functions with a simple GET request, while for deletion, we need to use a form since we are working within HTML, and we need to simulate the delete method.

Let’s now set up these edit and delete buttons to actually perform actions.

Let’s set up a route in the web.php file to handle the GET request for editing a post by its ID. The controller handling post editing is named ‘PostController’

We need to create a method in your PostController.php to handle the editing logic.

Let’s create a new view file named edit-post.blade.php.

To handle the PUT request for updating changes, you need to define a route in your web.php file. Here’s an example:

We need to create a function for the update; we are inventing function names. Let’s go to PostController.php. If we are not the author of the post, we should not be able to edit and update the post.

Let’s now set up the ability to delete. Let’s create the route again in web.php.

Let’s proceed to set up the delete functionality by defining a route in web.php and creating the corresponding function in PostController.php.

Displaying username

For the final details, let it display “by” and the username. Let’s start from the perspective of the blog post and examine the post.php model. We create a new function, a relationship…

This code assumes that your Post model has a foreign key user_id referencing the id column in the users table. Laravel will inspect this relationship and automatically generate a join query for us.
Adjust the relationship based on your specific database schema. Once the relationship is set up, you can use it in your views to display the username associated with each post.

For example, in our view: