CRUD(Create, Read, Update and Delete) operation in laravel 5.6
We are going to create a new Fresh Project "Myapp" Enter this Command on CMD.
composer create-project laravel/laravel Myapp
After entering this is Command It takes some time depends on your internet speed. After creating a new Laravel Project Now move to the First Step.
Insert Data Into database in laravel 5.6
Step 1: Create a Model, Controller, and Migration
We Need Model, Migration, and Controller to Start CRUD operation in Laravel 5.6. First, go to the Project path and enter the Following Command in CMD.
php artisan make:model Blog -mcr
After that its generate 3 new files.
app-> Blog.php.
database->migrations-> create_blogs_table.php
app->http->controller-> BlogController.php.
Step 2: Create a Database Table
Open create_blogs_table.php and add some column title and body as follows.
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
Before the migration, you should connect with your database. so open your .env file and add database, username and password field. (In my case my database name is "new blog" username is "root" and password is blank )
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=newblog
DB_USERNAME=root
DB_PASSWORD=
Now open CMD and enter a Command to migrate.
php artisan migrate
if you got some error like follows If not go to Step 3
In Connection.php line 647:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQ
L: alter table `users` add unique `users_email_unique`(`email`))
In Connection.php line 449:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Edit your app->providers->AppServiceProvider.php file
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Step 3: Create a form
Create a View Page For insert into the database.
{!! Form::open(array('route' => 'blog.store', 'method'=>'post')) !!} <div > <div > <div > <form> <div > <label for="exampleInputEmail1">Title</label> <input type=text name=title placeholder="Enter title"> </div> <div > <label for="exampleFormControlTextarea1">Blog Body</label> <textarea name=bodyrows="3"></textarea> </div> <button type=submit >Submit</button> </form> {!! Form::close() !!} </div> </div> </div>
After adding this is code may be Show Error "Class 'form' not found" so go to this link
Now Open BlogController.php and Edit
public function store(Request $request)
{
$this->validate($request,array(
'title' => 'required|max:255',
'body' =>'required',
));
$blog = new Blog;
$blog->title = $request->title;
$blog->body=$request->body;
$blog->save();
}
Now Test it, Hope It Will Work.
Read data from Database
Step 1
All a button to show all list of the blog on the view page.
<a href="{!! route('blog.index') !!}" class="btn btn-success">All Blog Post</a>
Now Add Some code on "BlogController.php" to fetch all records of Blog.
public function index()
{
$blog= Blog::all();
return view('view')->withBlog($blog);
}
Create a new page in View Folder "View.blade.php" and add some code to display data in the table format.
<div >
<div ></div>
<div >
<table >
<thead>
<tr>
<th>title</th>
<th>Blog</th>
</tr>
</thead>
<tbody>
@foreach ($blog as $key => $value)
<tr>
<td>{{$value->title}}</td>
<td>{{$value->body}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div ></div>
</div>
See the Result:
Edit and Updates data
in laravel 5.6
Step 1: Create an Edit view
Add A Edit Button on "view.blade.php" Page.
<a href="{{route('blog.edit', $value->id) }} " class="btn btn-sm btn-warning">Edit</a>
First Create an Edit View to Edit Our blog post "edit.blade.php".
<div > <div > <div > {!! Form::model($blog,['route'=>['blog.update',$blog->id],'method'=>'PUT']) !!} {{Form::label('title','Title:')}} {{Form::text('title',null,["class"=> 'form-control input-lg'])}} {{Form::label('body','Body:')}} {{Form::textarea('body',null,["class"=> 'form-control input-lg'])}} {!! Form::submit( 'Publish', ['class' => 'btn btn-success','name' => 'publish'])!!} {!! Form::close() !!} <hr> </div> </div> </div>
Now add some code to fetch Data in View page BlogController.php.
public function edit($blog)
{
$blog = Blog::find($blog);
return view('edit')->withBlog($blog);
}
And Add Some code to update data when you click on "Update Post" button.
public function update(Request $request, $blog)
{
$this->validate($request,array(
'title' => 'required|max:255',
'body' =>'required',
));
$blog = Blog::find($blog);
$blog->title = $request->title;
$blog->body=$request->body;
$blog->save();
return view('/welcome');
}
Delete data in laravel 5.6
Step 1: Add a Delete Button in View.blade.php page
{!! Form::open(['route'=>['blog.destroy', $value->id],'method'=>'DELETE'] ) !!}
{!! Form::submit('Delete',['class'=>'btn btn-danger btn-sm']) !!}
{!!Form::close() !!}
Now Add Some to delete Selected Blog post from the database.
public function destroy( $blog)
{
$blog = Blog::find($blog);
$blog->delete();
return view('/welcome');
}
I hope this post helps you if you have any dought ask in the comment box. Thanks.
Brijpal Sharma
Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...
0 Comments
You must be logged in to post a comment.