Professional Documents
Culture Documents
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
• DB_USERNAME to root
• DB_PASSWORD to blank
3. Run Migration
• Execute command in terminal
php artisan migrate
Schema::defaultStringLength(191);
Route::resource(‘posts’, ‘PostController’)
$post->title = $request->input(‘title’);
$post->body = $request->input(‘body’);
$post->save();
return redirect()route('posts.show',$postid);
}
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.
@endif
@if(count($errors) > 0)
@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.
$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.
<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.
return redirect()->route('posts.index');
}
$id pass as an argument, this
has the record to be deleted.