1 CS428 Web Engineering
Lecture 18
CRUD Operations with Laravel
• To make
Post model and migration
, type
command in terminal after navigation to
root directory.
php artisan make:model Post --migration
• Open
migration posts
, and add two more
columns
$table
string('title');
$table
text('body');
• Create database name
blog
in MySql
.
• Open .env file
in root directory. Change
• DB_DATABASE
name to
blog
• DB_USERNAME
to
root
• DB_PASSWORD
to
blank
• Execute command in terminal
php artisan migrate
• After running this command, laravel will create
posts
table
in database.
• In your appserviceprovider boot method, try adding
Schema::defaultStringLength(191);
• Best sure to import
Illuminate\Support\Facades\
Schema
at the top of the service provider.
• Next step is to
create a CRUD controller,
on
terminal navigate to root directory and type
the command
php artisan make:controller PostController --resource
• Open routes
web.php, and type
Route::resource(‘posts’, ‘PostController’)
• To view all the routes that application have,
on terminal type the command
php artisan route:list
• To insert data, we
create a form
.
• Create
folder post
in views and then create a
new file name
create.blade.php
• We will use
Html, Form helper class
to build
this form
create.blade.php
@extends('main') @section('content') <div class="row">
<div class="col-md-6 col-md-offset-3"> @if(Session::has('success'))
<div class="alert alert-success" role="alert">
<strong>Success:</strong> {{ Session::get('success') }}
</div>
@endif
<form method="post" {{ action(‘PostController@store') }}> <input type="hidden" name="_token" value="{{ csrf_token() }}">
<table class="table">
<caption class="text-center"><b>Student Registration Form</b></caption> <tr><td>Post Title:</td>
<td><input type="text" name=“title" class="form-control"></td></tr> <tr><td>Post Message:</td>
<td><textarea name=“body” class=“form-control”></textarea></td></tr> <tr><td></td>
• Now open PostController.php and
update
create function
by adding following code:
public function create(){
return view(‘posts.create’);
}
• To access the form type in URL
localhost:8000/posts/create
7. Update Controller
• To access the form type URL:
• After that we work on
store() method
in
PostController
, we perform two action in
store() method. This is the method that
stores data in database.
• Store
in the database
• Redirect
to another page
public function
store(Request $request)
{
$post =
new
Post;
$post->
title
= $request->input(
‘
title
’
)
;
$post->
body
= $request->input(
‘
body
’
)
;
$post->save();
session::flash(
'success'
,
'The blog post was
successfully save!'
);
return redirect()
route(
'
posts.show
'
,$post
id);
}
store() Method
This is the model we are
working with, so we create
we create an object of the
class Post, we need to tell our
• Flash Session is a session, that only exist for the current
request.
• Our next task is, if data successfully save in database,
We want to show a successful message to user. We use
flash() method.
• It takes two parameters, one is key and second is value.
I am going to set key as success and value is actually
the message that output.
session::flash(‘success’, ‘The blog post was successfully
save!’)
We use session class so we
need to tell our controller
• Update PostController.php
public function show($id)
{
return view(
'post.show'
);
}
• Setup a page for message.
• Create new file name
_messages.blade.php
inside
resource
views
partial folder.
• To show alert message on top of the page, add
this code
@include(‘partial._messages’)
on
@if(Session::has('success'))
<
div
class
=
"alert alert-success"
role
=
"alert"
>
<
strong
>
Success:
</
strong
>
{{ Session::get('success') }}
</
div
>
@endif
@if(count($errors) > 0)
<
div
class
=
"alert alert-danger"
role
=
"alert"
>
<
strong
>
Errors:
</
strong
>
<
ul
>
@foreach( $errors->all() as $error )
<
li
>
{{ $error }}
</
li
>
@endforeach
</
ul
>
</
div
>
@endif
• Type url localhost:8000/posts/create, the request goes to
create() method on PostController, and then create() method
redirect to create.blade.php in view.
• Create.blade.php is the page containing form, user will fill the
form and click on create post button.
• On create.blade.php, when user click on button, after filling the
form, request goes to store() method of PostController. In
store() method we save data into database and generate a
success message and then redirect to show() method of
PostController.
• On show() method will redirect to show.blade.php page of view.
• We have created
resource controller
, it
created many routes.
posts.index
is another
type of read that we are going to work on it,
• Open
PostController.php
file, we will perform
two task in
index()
method.
• Create a
variable and store
all the blog posts
in it from the database.
• Return a view
and pass in the above
variable.
public function
index()
{
// that pull all the data from the database
$posts = Post::
all();
return
view(
'post.index'
)->withPosts($posts);
}
• Create a new file
index.blade.php
and put
inside post folder in views.
• This is the file,
where we show all our posts
.
@extends('main')@section('title', '| All Posts')@section('content')
<
div
class
=
"row">
<
div
class
=
"col-md-10">
<
h1
>
All Posts
</
h1
>
</
div
>
<
div
class
=
"col-md-2">
<
a
href
=
"{{ route('posts.create') }}" class
=
"btn btn-lg btn-block btn-primary
btn-h1-spacing">
Create New Post
</
a
>
</
div
><
hr
/>
<
div
class
=
"col-md-12">
<
hr
/>
</
div
></
div
>
<
div
class
=
"row">
<
div
class
=
"col-md-12">
<
table
class
=
"table">
<
thead
>
<
th
>
#
</
th
><
th
>
Title
</
th
><
th
>
Body
</
th
><
th
>
Created At
</
th
><
th
></
th
>
</
thead
><
tbody
>
@foreach($posts as $post)
<
tr
>
<
th
>
{{ $post->id }}
</
th
>
<
td
>
{{ $post->title }}
</
td
>
<
td
>
{{ $post->body }}
</
td
>
<
td
>
{{ $post->created_at }}
</
td
>
<
td
><
a
href
=
"#" class
=
"btn btn-default">
View
</
a
><
a
href
=
"#" class
=
"btn
btn-default">
Edit
</
a
></
td
>
</
tr
>
@endforeach
</
tbody
></
table
></
div
></
div
>
@endsection
• To access the form type URL:
localhost:8000/posts
• Click on edit button, the request goes to edit() method on
PostController, and then edit() method redirect to
edit.blade.php in view.
• edit.blade.php is the file, where we kept the code for
form for updation.
• On edit.blade.php, when we click on update button, after
editing some data, request goes to update() method of
PostController.
• On update() method we kept the code that save updated
data into database.
• To update data, we will
create a new file
.
• Create a new file
edit.blade.php
and store it in
resource
views
post
@extends('main')
@section('title', '| Edit Blog Post') @section('content')
<div class="row">
{!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'PUT']) !!} <div class="col-md-8">
{{ Form::label('title', 'Title:') }}
{{ Form::text('title', null, ["class" => 'form-control input-lg']) }} {{ Form::label('body', 'Body:', ['class' => "form-spacing-top"])}} {{ Form::textarea('body', null, ["class" => 'form-control']) }} </div>
<div class="col-md-4">
<div class="well">
<dl class="dl-horizontal">
<dt>Create At: </dt>
<dd>{{ date('M j, Y h:ia', strtotime($post->created_at)) }}</dd> </dl>
<dl class="dl-horizontal">
<dt>Last Updated: </dt>
<dd>{{ date('M j, Y h:ia', strtotime($post->updated_at)) }}</dd> </dl><hr/>
<div class="row"><div class="col-sm-6">
{!! Html::linkRoute('posts.show', 'Cancel', array($post->id), array('class' => 'btn btn-danger btn-block')) !!} </div>
<div class="col-sm-6">
{{ Form::submit('Save Changes', ['class' => 'btn btn-success btn-block']) }} </div></div></div></div>
{!! Form::close() !!} </div>