The complete Lavarel framework development tutorial

Powered by Blogger.

Tuesday 7 March 2017

Laravel 5- Insert data into MySQL database



The database is the backbone of any web development. We often need to store the user data into our database and further retrieve the data and display in the web pages. In this tutorial you will learn how you can insert data into MySQL database using Laravel 5. MySQL is the most popular database management system used with PHP and PHP frameworks.

Laravel 5- Insert data into MySQL database- Database and Model

The very first thing we have to do is creating a database for our web application. There are a number of ways you can create a database. Some of them can be-
  • Laravel Migration- It helps creating database using php. Learn more- https://laravel.com/docs/5.4/migrations
  • phpmyadmin (recommended)- It is a tool to manage MySQL databases using a web browser. It makes managing database very easy. Learn more about phpmyadmin- https://www.phpmyadmin.net/
  • SQL- You can run sql queries using terminal
Create a database using any of the above method named blog (You can give it any name). Add a table named posts and then add five columns- id, title, body, created_at and updated_at.
The next thing you have to do is create a model for corresponding database.
php artisan make:model Post
To learn more about Laravel Model, read this-

Eloquent ORM - Laravel Models Tutorial

Laravel 5- Insert data into MySQL database- Configuration

To insert data into MySQL database you need to configure your database with your web app. Open .env file from the root directory and update these fields.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog  // your database name
DB_USERNAME=root  // your database username
DB_PASSWORD=      // your database password

Laravel 5- Insert data into MySQL database- Routes and Controllers

For a very basic example, we just need to add two routes. This is enough for now to learn how can you insert data into MySQL database.
url Request Type Points to Use
posts/create GET PostController@create Display a form for writing post data
posts POST PostController@store Store data into database
Create a controller named PostController.
php artisan make:controller PostController
In the PostController define two functions.

create

public function create()
{
    return view('posts.create');
}
This will display a view named create inside resources/views/posts directory.

store

public function store(Request $request)
{
    $post = new Post;
    $post->title = $request->title;
    $post->body = $request->body;

    $post->save();
}
This will create a instance of Post model, set all the attributes and finally will save data into database. We don't need to set attribute for columns created_at and updated_at. These are managed by laravel.

Laravel 5- Insert data into MySQL database- View

Above, we have define a route and a function to display a form so that we can enter data and click the save button to save data into database. We are going to create that form. Create a new file called create.blade.php inside resources/views/posts directory (You need to create posts directory by yourself).
<!DOCTYPE html>
<html>
<head>
 <title>Add new Post</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<form class="form-horizontal" method="POST" action="{{url('posts')}}">
<fieldset>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="title">Title</label>  
  <div class="col-md-4">
  <input id="title" name="title" type="text" placeholder="" class="form-control input-md">
    
  </div>
</div>

<!-- Textarea -->
<div class="form-group">
  <label class="col-md-4 control-label" for="body">Body</label>
  <div class="col-md-4">                     
    <textarea class="form-control" id="body" name="body"></textarea>
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for=""></label>
  <div class="col-md-4">
    <button id="" name="" class="btn btn-success">Save</button>
  </div>
</div>

{{csrf_field()}}
</fieldset>
</form>

</body>
</html>
In the form, I have added a helper {{csrf_field()}}. The CSRF (cross-site request forgery) helps our site from malicious exploit, where unauthorized command are being performed on behalf of an authenticated user. Whenever you are performing a POST, PUT or DELETE request from your HTML form, you need to add this helper within your form.
Finally test your code. To insert data into MySQl database visit http://your-site-url/posts/create, enter title and body and click on the save button.

Conclusion

Here, you learned how you can insert data into MySQL database in Laravel 5. Laravel makes web development very easy. We don't need to make connections with the database, neither writing sql queries.

Follow us to learn more about Laravel.

4 comments:

  1. no routing done to the post.create

    ReplyDelete
  2. i have done the same procedure but nothing is being inserted into the database

    ReplyDelete
  3. I hope you would be doing well. Dear admin your site is really easy to understand and one of the best in the town. I had gone through your site and I can confidently say that your site is free of bugs. Therefore, everyone should use this website. However, we also provide website development tools. Here is the link of our site jsononline

    ReplyDelete