banner image
Sedang Dalam Perbaikan

Insert data in Laravel


This is another article based on Laravel. The topic is inserting data into a database using a form. Here I'm going to continue the same project I created previously. Otherwise this article will be lengthy. The previous article is; Fetch data belongs to an ID
But still you can get my code snippets separately and use in your own way...

The work we have done so far:
  1. Create a project called TestApp
  2. Create views and routes
  3. Create model and resource controller to handle data
  4. Fetch and display database records
  5. Fetch and display data according to an ID
Today we will do the data insertion part to the database.

Open the project and run it first.
Then we need to create and adjust navbar links to navigate to the pages including the page for inserting data.

resources/views/partials/navbar.blade.php

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/">Laravel Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="navbarColor02">
<ul class="navbar-nav ml-auto">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/posts">Blog</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link" href="/posts/create">Create a Post</a>
</li>
</ul>
</div>
</nav>

Now we can go to the insert post page when we click on Create a Post navbar link. So, we have to create a view file to display the input fields with a form.
Here, there's an important thing to know. There's a package called Laravel Collective which makes easy form building.
Visit here : Laravel Collective - HTML

We have to install this package using cmd. Remember to do these after navigating to your project folder from cmd or terminal. Look at the installation guide here. Just follow the steps. All the steps are required!!!!

After the installation you can use a set of amazing form binding codes..Site is giving the full documentation. For more details, read it. Now we can create the view to input data.

resources/views/posts/create.blade.php

@extends('layouts.master')
@section('content')
@include('partials.navbar')
<div class="container">
<h1 style="margin-top: 30px;">Create a Post</h1><br>
<br><br>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8">
@include('partials.messages')
{!! Form::open(['action' => 'PostsController@store', 'method' => 'POST']) !!}
<div class="form-group">
{{ Form::label('title', 'Title of the Post ', ['class' => 'form-label'] )}}
{{ Form::text('title', '', ['class' => 'form-control', 'placeholder' => 'Give a Title', 'id' => 'title']) }}
</div>
<div class="form-group">
{{ Form::label('body', 'Body of the Post ', ['class' => 'form-label'] )}}
{{ Form::textarea('body', '', ['class' => 'form-control', 'placeholder' => 'Give a Description', 'id' => 'body']) }}
</div>
<br>
{{ Form::submit('Post', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
</div>
<div class="col-lg-2"></div>
</div>
</div>
{{-- @include('partials.footer') --}}
@endsection

You can see the binding part.. This {!! !!} can be used since we have included the package in our project. Otherwise this will give errors. View will be like this..

You can see a new include code just before the form. 
@include('partials.messages')

What is it? It is for the success and fail messages. When you submit the form without filling a field, errors should be displayed. After submission, message should be shown. Those messages are shown according to the logic included in this messages.blade file. This is the code...

resources/views/partials/messages.blade.php

@if(count($errors)>0)
@foreach($errors->all() as $error)
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{$error}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endforeach
@endif

@if(session('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{session('success')}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif

@if(session('error'))
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{session('error')}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif

Errors will be shown like this when you submit without data..I use Bootstrap Dismiss-able Alerts to design the messages. They can be removed using the cross mark in the message.


Form action has been set as PostsController@store. We are going to implement this function.

store function : PostsController


public function store(Request $request)
{
// input validations
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
// create post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
// redirect to the create page with success message
return redirect('/posts/create')->with('success', 'Post created');
}

Ok!!! Now we have come to the end. Insert some data and click on Post button. Data will be submitted to the database. 




We have completed the tutorial. You can insert data and try to see them in the posts page. Laravel provides an easy way of inserting data. It's so easy according to my idea. My next articles will handle the Editing and Deleting functions for these data. I'm sure those articles will also be interesting. So, wait for it. Till then Good Bye!




Insert data in Laravel Insert data in Laravel Reviewed by DAL on March 05, 2018 Rating: 5

No comments:

Powered by Blogger.