You are on page 1of 59

CS428 Web Engineering

Lecture 18
CRUD Operations with Laravel
(Laravel – V)

1
Create/Insert Data in Laravel
1. Create Post Model
• 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');
2. Create Database
• 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
3. Run Migration
• 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.
4. Create CRUD Controller
• Next step is to create a CRUD controller, on
terminal navigate to root directory and type
the command

php artisan make:controller PostController --resource


5. Create Route
• 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


6. Create Form
• 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>
<td><input type="submit" name="submit" value="Add Student" class="btn btn-
primary"></td></tr>
</table>
</form>
</div>
</div>
@endsection
7. Update Controller
• Now open PostController.php and update
create function by adding following code:

public function create(){


return view(‘post.create’);
} It will first call the view name
create, resided in posts folder

• To access the form type in URL


localhost:8000/posts/create
8. Access Form
• To access the form type URL:
localhost:8000/posts/create
9. store() Method
• 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
store() Method
public function store(Request $request)
This is the model we are
{ working with, so we create
$post = new Post; instance of the model.

$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);

}
we create an object of the
class Post, we need to tell our
controller about it.
Success Message
• 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 flash method of
Session class, to show a
successful message to user.
We use session class so we
need to tell our controller
about it.
Update PostController.php
• Update PostController.php

public function show($id)


{
return view('post.show');
}
_messages.blade.php
• 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
main.blade.php , before @yield(‘content’)
_messages.blade.php
@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
How It Works
• 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.


Read Data in Laravel
Reading Data
• We have created resource controller, it
created many routes. posts.index is another
type of read that we are going to work on it,
Update PostController
• 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.
Index()
public function index()
{
// that pull all the data from the database

$posts = Post::all();

return view('post.index')->withPosts($posts);

}
Index.blade.php
• Create a new file index.blade.php and put
inside post folder in views.

• This is the file, where we show all our posts.


Index.blade.php
@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
Output
• To access the form type URL:
localhost:8000/posts
Update Data in Laravel
How It Works
• 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.
Edit.blade.php
• 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>

@stop
For updating method PUT or
PATCH will be use only
Update PostController
• Open PostController.php , for update we will work
on update() method. There we will perform four
actions.

• Validate the data


• Save the data into database
• Success message
• Redirect to posts.show
$id pass as an argument, this
has the record to be updated.
Delete Data in Laravel
Delete
• Delete does not have forward facing page, its
strictly a controller method.

• Open show.blade.php , alter the file and instead of


delete button, create a form submit button
{!! Form::open(['route' => ['posts.destroy', $post->id],
'method' => 'DELETE']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger
btn-block']) !!}
{!! Form::close() !!}
destroy() Method
• Open PostController.php , for delete we will work on
destroy() method.

public function destroy($id)


{
//
$post = Post::find($id);
$post->delete();
Session::flash('success', 'The post was
successfully deleted.');

return redirect()->route('posts.index');
}
$id pass as an argument, this
has the record to be deleted.

You might also like