আগামী ৩০ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

CRUD With Pagination In Laravel

Hello guyz!! You know what actually we have such a great way of learning things from the internet. It’s an ocean of knowledge. And in this part of web development it has got no boundaries. Hope that we would going to learn something from here today also.

First of all I want to advise you to those who don’t know nothing about migrations or laravel quite well please visit my tutorials of laravel so that we can work fine. If you already visited these tutorials or if you’ve idea about the methods of artisan, migration than let me welcome to this tutorial.

Now in this tutorial we’re going to learn the CRUD System With Pagination Using Laravel. Now let’s start our tutorial.

For the CRUD system at first we need some sample data which we’re going to show in the view with pagination & also guess what? I’m going to use Twitter Bootstrap for the basic layout also. Now you should add something in your table but first of all you should edit your database config file & the app key also. If you don’t know how to do these things please go to my other tutorials given in the link above. Now for the database you need to install migrate on your laravel application. And then simply add the table & some sample data using migration. Follow the steps below to do that. Add you command prompt or terminal & give the command below:

php artisan migrate:make create_authors_table

After that you can find a new file named after the command that you’ve given which is [timestamp_value]create_authors_tabel in your migration folder. Open it and put the code from below in the file.

class Create_Authors_Table {

public function up()

{

Schema::create('authors',function($table){

$table->increments('id');

$table->string('name');

$table->text('bio');

$table->timestamps();

});

}

public function down(){

Schema::drop('authors');

}

}

Now write down another command in your command prompt or terminal which one’s given below:

php artisan migrate:make add_authors

Now you can notice that there is another file created with the name that you’ve given in your migration folder. Just open it & give some sample data to store in the database. Put the code from below & paste it in the file. Remember these will be our sample data.

class Add_Authors {

public function up(){

DB::table('authors')->insert(array(

'name' => 'Adnan',

'bio' => 'Am I a good coder actually? May be not that\'s why i can\'t get a single work done...',

'created_at' => date('Y-m-d H:m:s'),

'updated_at' => date('Y-m-d H:m:s')

));

DB::table('authors')->insert(array(

'name' => 'tisha',

'bio' => 'She\'s a good & hardworking coder actually',

'created_at' => date('Y-m-d H:m:s'),

'updated_at' => date('Y-m-d H:m:s')

));

DB::table('authors')->insert(array(

'name' => 'Ovi',

'bio' => 'Nothing to say about him!!',

'created_at' => date('Y-m-d H:m:s'),

'updated_at' => date('Y-m-d H:m:s')

));

DB::table('authors')->insert(array(

'name' => 'Masud',

'bio' => 'What a guy he is.. An amazing coder.',

'created_at' => date('Y-m-d H:m:s'),

'updated_at' => date('Y-m-d H:m:s')

));

DB::table('authors')->insert(array(

'name' => 'Jaman',

'bio' => 'he\'s a good & hardworking actually. He is gonna be a zend among us',

'created_at' => date('Y-m-d H:m:s'),

'updated_at' => date('Y-m-d H:m:s')

));

}

public function down(){

DB::table('authors')->delete(1);

DB::table('authors')->delete(2);

DB::table('authors')->delete(3);

DB::table('authors')->delete(4);

DB::table('authors')->delete(5);

}

}

Now go to your command prompt or terminal again & write down the below code to run the migration & add the table, sample data to your db.

php artisan migrate

Now go to your browser type localhost/phpmyadmin & check if the data inserted in the db correctly. So if it has been inserted quite well than our data insert works completed successfully. Now it’s time for the raw coding & get our data back to the frontend with pagination & of course with the bootstrap layout.

Now we need to fetch the information using our model and also it’s actually best to validate the data when inserting & editing the data in the form. So to do that we need to add some validation rules also. Go to your model & create a file name it author.php we’ve to keep one thing in mind that laravel suggests us to keep the file name of a model single number & in controller plural number, that’s why I’ve used author instead of authors. Now put the code from below to your file. We’ll be using laravel’s amazing system Eloquent. For more details please go to the documentation of Eloquent<link of doc in lara> in laravel site.

//we will extend author class

//to eloquent as we're going

//to use this option which is

//given by laravel

class Author extends Eloquent{

//this is the table name

public static $table = 'authors';

//these are some rules that will

//help us in our data insertion

//and in editing

public static $rules = array(

'name' => 'required|min:5|max:10',

'bio' => 'required|min:15|max:200'

);

//Validation process will come here to

//validate the given data

public static function validate($data){

//validator is a class that will

//make our data validate

//it's made by the laravel community

return Validator::make($data, static::$rules);

}

}

In the code above I’ve commented out all the things so that you could understand every single code I’ve wrote down. Now I hope you’ve understood the code it’s the end of our model part.

Now go to the controller & create a file name it authors.php here you can see that I’ve given a plural name in here according to laravel said. So you just do that also & now just put the code from below and paste it at the beginning of your code.

class Authors_Controller extends Base_Controller{

//here i've used a restful property

//so that i can use what ever http varb

//i want to use instead of action_ http varb

public $restful = true;

//this is the index controller

//it'll get the view page

public function get_index(){

$authors =  Author::order_by('id', 'desc')->paginate(3); //show 3 record in each page

return View::make('authors.index')

->with('title','Authors Bio')

->with('authors',$authors);

}

}

In get_index method I’m fetching information using my model “Author” is my model name class & it got an static method order_by so that i can have the item according to my wish & also using “paginate(3)” to show only 3 items each page then returning a view “author.index”, I’ve also using with method to send a title to the view page also the paginator class. As we’ve given the name author.index the view name now go to the view folder & in there create a folder named author also in there a file named index.blade.php here we’re also going to use the blade template engine of laravel to shorten our php code. Now put the code from below & paste it in your file.

@layout('layouts.default')

<!--this the default layout directory-->

<!--this section will contain everything

which will be shown in our default layout-->

@section('content')

<div class='container' align='center'>

<h1>Authors Bio Page</h1>

<table width="500" border='1' class='table-striped'>

<tr>

<th scope='row'>Name</th>

<th scope='row'>Bio</th>

<th scope='row'>Updated At</th>

<th scope='row'>Action</th>

</tr>

@foreach($authors->results as $author)

<tr>

<td> {{$author->name}} </td>

<td> {{$author->bio}} </td>

<td><small> {{$author->updated_at}} </small></td>

<tr>

@endforeach

</table><br>

<table>

<tr>

<!--to show the pagination field-->

{{$authors->links()}}

</tr>

</table>

</div>

@endsection

This is the view page, that we’ve created in here. You should always notice that ‘@layout’ function should not be in the second line of your coding otherwise it’ll show you nothing. Now it’s time to create our layout file. Go to the view folder and create a new folder name it layouts and inside that folder create a new page name it default.blade.php & put the code given below:

<!DOCTYPE html>

<html>

<head>

<title>{{ $title }}</title>

{{ HTML::style('css/bootstrap.css') }}

{{ HTML::script('js/bootstrap.js')}}

</head>

<body>

@yield('content')

</body>

</html>

In here we’re yielding our content name. Just visit the previous post to know about the yield thing.

Now go to routes so that you could give the route to go to the view page via controller. In route.php put the code below & paste it into your application route.

//this route is for the authors index

Route::get('authors', array('as'=>'authors','uses'=>'[email protected]'));

Now we’re using a name for the route as we’re going to redirect to it many times. So to that we use a key called ‘as‘ key & named this route ‘authors‘ & used an ‘uses’ key to show the route in which controller & method to visit. That’s our view route. Now go to the browser write down the below url address to view your data in the browser.

URL::http://localhost/yoursourcename/public/authors

In the above url laravel is my application name. You can give your application name also as you like. And if no  error occurs you may visit a page like the below one.

viewpagewithpaginationwithoutaction

Now that we’ve created our view page seeing our data from the database and also we can pagination from one page to another that’s working fine also. Now when you’re using bootstrap you should notice that your pagination will be not like the picture above given. To do like that you should add some css coding in the boostrap.css file, so open it and search a name with “.pagination” after searching you’ll find some class name with pagination just replace it with the code below & save it voila your pagination style with bootstrap will be fine now.

.pagination {

a.previous_page,span.previous_page {

border-left: 1px solid #ddd;

}

span {

float: left;

padding: 0 14px;

line-height: (@baseLineHeight * 2) - 2;

text-decoration: none;

border: 1px solid #ddd;

border-left-width: 0;

}

}

Now it’s time for us to add some authors into the database whereas it comes for the creation of CRUD system. For that go to the authors controller and create a public function just like the below coded under your “get_index” function.

//browse to get a new author page

public function get_new(){

return View::make('authors.new')

->with('title','Add New Author');

}

By this method we’re going to create our author insertion page. So now go to the authors folder inside view folder and make a new file and name it new.blade.php and put the code from below & paste it:

@layout('layouts.default')

@section('content')

<div class='container'>

{{Form::open('authors/create','POST')}}

<fieldset>

<div id="legend" class="">

<legend class="">Add An Author</legend>

</div>

<div class="control-group">

<!-- Text input-->

<label class="control-label" for="input01">Name:</label>

<div class="controls">

<input type="text" name="name" placeholder="Enter Your Name Here" value="{{Input::old('name')}}">

</div>

</div><div class="control-group">

<!-- Textarea input-->

<label class="control-label" for="input01">Biography:</label>

<div class="controls">

<textarea name='bio' placeholder="Enter Your Biography Here">{{Input::old('bio')}}</textarea>

</div>

</div>

<div class="controls">

<input type="submit" name="add_author" value="Add Author"/>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<p> {{HTML::link_to_route('authors','Return To The Main Page')}} </p>

</div>

</fieldset>

{{Form::close()}}

</div>

@endsection

Now go to the route to create a route to this page & put the code from below:

//this route is for new authors create

Route::get('authors/new', array('as'=>'new_author','uses'=>'[email protected]'));

Here we’re going to use as keyword to name the route new_author ok. Now go to the page & see if the page is loading correctly. But going to that page isn’t ok so add a new link to the index.blade.php file after the h1 tag  you can see in the below code:

<p> {{HTML::link_to_route('new_author', 'Add New Author')}} </p>

This code will create a new link to the index page so that you can easily go to the new authors page. Or you can directly enter into the page by typing the following url:

URL::http://localhost/yoursourcename/public/authors/new

Then you can find the page looks like the picture below:

createauthor

Now for inserting that method you should create a method to insert the data that you wanted. To do that go to the authors controller & paste the code below after your previous method in that file.

//insert new author

public function post_create(){

&nbsp;

//validate all input using the validate

//static method under author class.

$validation = Author::validate(Input::all());

//if the validation fails redirect user to

//the insert new author page

if($validation->fails()){

return Redirect::to_route('new_author')->with_errors($validation)->with_input();

}

//else create create new author

else{

Author::create(array(

'name'=>Input::get('name'),

'bio'=>Input::get('bio')

));

//and then redirect user to the index page

return Redirect::to_route('authors')

->with('status_message','Author Was Created Successfully');

}

}

When redirecting to the index page in the upper code notice that we’ve used to_route method & inside of that we’ve used the name of the route that we’ve given earlier so now I think you’ve understood why the name of the route is important. And also you can see that we’re giving away a flash message to the user that his new input just inserted successfully. So to see that message go to the default.blade.php template & write down the code from below before the yield method see the code to have more explanation.

@if(Session::has('status_message'))

<p align='center' style="color:green;"> {{Session::get('status_message')}} </p>

@endif

@yield('content')

Here we can see that if there’s an message set so than via the session class and it’s get method we’re giving our status message.

Now to create this author we need to show the route the controller method so go to the routes.php and add the following code remember one thing we’ve told the form in “form_open()” to go to the “authors/create” controller so we’ve to set the route according to that.

//this route is for inserting item in db

Route::post('authors/create', array('uses'=>'[email protected]'));

Now as we’ve use validation if we try to enter false thing like we set in the model validation rules you’ll get error else you’ll pass, so just go and let’s see if that things right or not. If right than you’ll get an error message for the wrong input. To see the error message you must set the error message into the file so let’s do that go to the new.blade.php file and in there just add the code before the form_open() method.

@if($errors->has())

<ul>

{{$errors->first('name', '<li>:message</li>')}}

{{$errors->first('bio', '<li>:message</li>')}}

</ul>

@endif

See the picture below so that you can be sure your one’s just like mine.

validationoninsertion

Now the insertion is done. It’s time for us to edit the input. Here it come the update part of CRUD system. So now to do that what you’ve to do is just go to the controller to create a new method to have the info which I want to update. So just put the code from below and paste it into yours:

//get the edit form

public function get_edit($id){

return View::make('authors.edit')

->with('title','Edit Author')

->with('author', Author::find($id));

}

In this method we’re gonna need the ID of the raw that I want to edit. So to do that let’s go the index.blade.php file and give a edit link or button by which we can get our update page with the correspondent data via the id given. So to do that just paste the code into your ones.

<td>

<button class='btn btn-success'>

{{HTML::link_to_route('edit_author','Edit',array($author->id))}}

</button>

</td>

Add a new raw into the foreach loop of your page & it’ll show the edit button into your action column just like the picture below and you can also see that on that button we’re passing an array with our author ID that will do our work.

editbuttonadded

Now as we’ve created our edit button it’s time for to set the routes. Just add the code from given below:

//this route is for update author page

Route::get('author/(:any)/edit', array('as'=>'edit_author','uses'=>'[email protected]'));

In the above code we can see a li’l difference between the routes that we’ve coded earlier. It’ s because we’re passing an id with the edit button and the method in the class also will have to have the id to view the edit page with correspondent info so for that in here we set ‘author/(:any)/edit’ this :any means that here it can be an integer on anything else like id etc. Now that we’ve set our routes it’s time for us to create a view file in the view folder for edit our authors. To do that go to the authors folder inside the view folder and create a file name it edit.blade.php and put the code from the below:

@layout('layouts.default')

@section('content')

<div class='container'>

<h1>Editing {{$author->name}}</h1>

@if($errors->has())

<ul>

{{$errors->first('name', '<li>:message</li>')}}

{{$errors->first('bio', '<li>:message</li>')}}

</ul>

@endif

{{Form::open('authors/update','PUT')}}

<fieldset>

<div id="legend" class="">

<legend class="">Edit An Author</legend>

</div>

<div class="control-group">

<!-- Text input-->

<label class="control-label" for="input01">Name:</label>

<div class="controls">

<input type="text" name="name"  class="input-xlarge" value="{{$author->name}}">

</div>

</div><div class="control-group">

<!-- Textarea input-->

<label class="control-label" for="input01">Biography:</label>

<div class="controls">

<textarea name='bio'>{{$author->bio}}</textarea>

</div>

</div>

<div>

<input type="hidden" name="hidden_id"  value="{{$author->id}}">

<input type="submit" name="edit_author" value="Update Author"/>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<p> {{HTML::link_to_route('authors','Return To The Main Page')}} </p>

</div>

</fieldset>

{{Form::close()}}

</div>

@endsection

In this view code we’re getting the error messages if there’s an error with the input text and then update button to update the author. But it’ll not work correctly unless you give the update order to the controller. So to update the info create a method into the authors controller, just put the code below:

//update author method

public function put_update(){

//fetch the hidden id via input get method

$id = Input::get('hidden_id');

$validation = Author::validate(Input::all());

//if validation fails redirect to edit page

if($validation->fails()){

return Redirect::to_route('edit_author',$id)->with_errors($validation);

}

//else update the info

else{

Author::update($id, array(

'name'=>Input::get('name'),

'bio'=>Input::get('bio')

));

//return to authors view with a success message

return Redirect::to_route('authors')

->with('message', 'Author Was Updated Successfully');

}

}

As you can see we’ve given the method name put_ varb because we’ve told the form that the method will be put not get or post. Now we’ve set the controller it’s time for the route. Go to the routes file and create a route for the update option to work, just put the code from below:

//this route is for update the author

Route::put('authors/update', array('uses'=>'[email protected]'));

Now after setting the route if you want to update an author you can try thyself. It’ll work correctly updating the form.

Now it’s time for the delete method. Here comes the delete of CRUD system. For deleting item we’ll also need to fetch the id of the correspondent data that is to be deleted. For that go to the view file index.blade.php and add an action button which is delete. To do that just put the code below :

<td>

<button class='btn btn-success'>

{{HTML::link_to_route('edit_author','Edit',array($author->id))}}

</button>

{{Form::open('author/delete','Delete')}}

{{Form::hidden('id', $author->id)}}

<input type="submit" name="edit_author" value="Delete"/>

{{Form::close()}}

</td>

Here you can see we’ve put an delete button after the edit button. You can also notice that we’ve created an form for the deletion. Form is needed to delete the data as we’ve to pic the id it. We just took a hidden input & in there we’re storing our author id. That’s the thing we need in the controller method. Looks like you’ve got a look just like the below picture with all action in the view.

allviewafterdeletebuttonset

Now it’s time for us to create our delete controller but before that let us create our route first. To do that go to the routes file and put the code below:

//this route is for delete the author

Route::delete('author/delete', array('uses'=>'[email protected]'));

In here as you can see we’re using the delete method which is delete http varb which indicates to the author/delete method in the controller. So our routes made successfully it’s time for us to create our method for deletion in the controller. Go to authors controller & create a method just put the code below:

//delete an author using delete http varb

public function delete_erase(){

//find an id of author using the input field

//which we've used on the view page

Author::find(Input::get('id'))->delete();

//redirecting to the authors page with the successful message

return Redirect::to_route('authors')

->with('message', 'Author Was Deleted Successfully');

}

So after doing this your code will be finished and also the finishing of the CRUD system. If you’d liked this tutorial please do leave a comment. If you want to download the source code feel free to download it from the download link.

An enthusiastic of work with over 2+ years of experience. Extensively experienced on wordpress, Codeigniter, Laravel. ##Visit my github page (https://github.com/ashawkat) ##Visit my blogging page where I spread out my knowledges around all other people (http://w3programmers.com/author/tanim) If you want to hire me then you can contact me via email or skype. Skype: ashawkat89 Email: [email protected]
6 comments on “CRUD With Pagination In Laravel
  1. Thank You for the Tutorial. Actually I am new to Laravel and your tutorial is the closest I found online in line to what I want to achieve. The problem I am facing is that I cannot run the the application because I am using laravel 4.
    Do you have the Laravel 4 version of your tutorial or any link I can use to create a crud table.

  2. Really love your tutorials. Really wish you could speed up with adding more content. I specifically need something on login and user registration

Leave a Reply

Your email address will not be published. Required fields are marked *