Sunteți pe pagina 1din 9

Creating a Blog Using Laravel 4 Part 1: Models and

Seeding

Laravel Quick Installation and Setup


I will assume that you have a working installation of Laravel 4. Otherwise, you can
follow these steps to install and setup Laravel 4:

Install Laravel 4 by following instructions provided here.

Create a database using the MySQL terminal client:

[usm4n@usm4n-desktop][~]

mysql -u root -p

Enter password:

mysql> create database laravel;


Query OK, 1 row affected (0.00 sec)

Configure database in /app/config/database.php:


1. 'mysql' => array(
2.

'driver'

=> 'mysql',

3.

'host'

=> 'localhost',

4.

'database' => 'laravel',

5.

'username' => 'root',

6.

'password' => 'very_secret_password',

7.

'charset' => 'utf8',

8.

'collation' => 'utf8_unicode_ci',

9.

'prefix'

10.

=> '',

),

Creating Database Migrations


In this section, we will create database tables for our blog application using Laravel
Database Migrations. Our application will be utilizing posts and comments tables to
store articles and user comments respectively. (Read more on migrations here)
QUICK TIP:
We use artisan migrate:make create_tablename_table and artisan migrate commands
to create and run migrations respectively.
Migration class for posts table:

1.

<?php

2.

use Illuminate\Database\Migrations\Migration;

3.

use Illuminate\Database\Schema\Blueprint;

4.
5.

class CreatePostsTable extends Migration {

6.
7.

/**

8.

* Run the migrations.

9.

10.

* @return void

11.

*/

12.

public function up()

13.

14.

Schema::create('posts', function(Blueprint $table) {

15.

$table->increments('id');

16.

$table->string('title');

17.

$table->string('read_more');

18.

$table->text('content');

19.

$table->unsignedInteger('comment_count');

20.

$table->timestamps();

21.

$table->engine = 'MyISAM';

22.

});

23.

DB::statement('ALTER TABLE posts ADD FULLTEXT search(title, content)');

24.

25.

/**

26.

* Reverse the migrations.

27.

28.

* @return void

29.

*/

30.

public function down()

31.

32.

Schema::table('posts', function(Blueprint $table) {

33.

$table->dropIndex('search');

34.

$table->drop();

35.

});

36.
37.

}
}

Note that, I have used $table->engine='MyISAM' and added a composite fulltext


index using title and content columns. This will allow us to utilize MySQL fulltext
search on posts table.
Code for comments table migration:

1.

<?php

2.
3.

use Illuminate\Database\Migrations\Migration;

4.

use Illuminate\Database\Schema\Blueprint;

5.
6.

class CreateCommentsTable extends Migration {

7.
8.

/**

9.

* Run the migrations.

10.

11.

* @return void

12.

*/

13.

public function up()

14.

15.

Schema::create('comments', function(Blueprint $table) {

16.

$table->increments('id');

17.

$table->unsignedInteger('post_id');

18.

$table->string('commenter');

19.

$table->string('email');

20.

$table->text('comment');

21.

$table->boolean('approved');

22.

$table->timestamps();

23.

});

24.

25.

/**

26.

* Reverse the migrations.

27.

28.

* @return void

29.

*/

30.

public function down()

31.

32.

Schema::drop('comments');

33.

34.
35.

The post_id field will help us in defining one to many relationship using Eloquent
ORM seamlessly. We will use approved field of comments table for comments
moderation purpose. We will cover the users table in Authentication Section.

Creating Models Using Eloquent ORM

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord
implementation for working with your database. Each database table has a
corresponding Model which is used to interact with that table.Laravel Eloquent ORM
Documentation

We use singular variants of table names as our Eloqent Model names, this
convention helps the Eloquent to figure out the table to be used with a particular
Model. For instance: if the name of the Model is Post Eloquent will assume a table
with name posts to be used.
Here is the code for our Post and Comment Models:

1.

<?php

2.

// file: app/models/Post.php

3.

class Post extends Eloquent {

4.
5.

public function comments()

6.

7.

return $this->hasMany('Comment');

8.

9.
10.

11.

// file: app/models/Comment.php

12.

class Comment extends Eloquent {

13.
14.

public function post()

15.

16.
17.

return $this->belongsTo('Post');
}

18.

Seeding Database Tables


We will use a single PostCommentSeeder class to populate
both posts and comments tables.
QUICK TIP:
We use artisan db:seed command to seed the database.
Code for PostCommentSeeder :

1.

<?php

2.
3.

class PostCommentSeeder extends Seeder {

4.
5.

public function run()

6.

7.

$content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.

8.
9.

Praesent vel ligula scelerisque, vehicula dui eu, fermentum velit.


Phasellus ac ornare eros, quis malesuada augue. Nunc ac nibh at mauris
dapibus fermentum.

10.

In in aliquet nisi, ut scelerisque arcu. Integer tempor, nunc ac lacinia cursus,

11.

mauris justo volutpat elit,

12.

eget accumsan nulla nisi ut nisi. Etiam non convallis ligula. Nulla urna augue,

13.

dignissim ac semper in, ornare ac mauris. Duis nec felis mauris.';

14.

for( $i = 1 ; $i <= 20 ; $i++ )

15.

16.

$post = new Post;

17.

$post->title = "Post no $i";

18.

$post->read_more = substr($content, 0, 120);

19.

$post->content = $content;

20.

$post->save();

21.
22.

$maxComments = mt_rand(3,15);

23.

for( $j = 1 ; $j <= $maxComments; $j++)

24.

25.

$comment = new Comment;

26.

$comment->commenter = 'xyz';

27.

$comment->comment = substr($content, 0, 120);

28.

$comment->email = 'xyz@xmail.com';

29.

$comment->approved = 1;

30.

$post->comments()->save($comment);

31.

$post->increment('comment_count');

32.

33.

34.
35.

}
}

The outer for loop creates a new Post Model on each iteration and saves it after
setting the properties: title , read_more , content . The inner loop creates random
number of comments for each Post and increments
the comment_count in posts table.

The artisan tinker Command

The Artisan CLI tool provides us with an easy way to interact with Laravel application
from command line. We use artisan tinker command to use the interactive shell. Lets
practice some Eloquent queries on our test data.
[usm4n@usm4n-desktop][~]
artisan tinker
>

Find By Id Using find()


>$post = Post::find(2);
>$post->setHidden(['content','read_more','updated_at']);
>echo $post;
{"id":"2","title":"Post no 2","comment_count":"7","created_at":"2014-01-06 09:43:44"}

Limit No Of Records Using take() And skip()


>$post = Post::skip(5)->take(2)->get();
>foreach($post as $value) echo "post id:$value->id ";
post id:6 post id:7

Using select() And first()


>$post = Post::select('id','title')->first();
>echo $post;
{"id":"1","title":"Post no 1"}

Using where() With select()


>$post = Post::select('id','title')->where('id','=',10)->first();
>echo $post;
{"id":"10","title":"Post no 10"}

Getting Related Records Using Dynamic Property


>$post = Post::find(4);
>echo $post->comments[0]->commenter;
xyz

Getting Parent Records From Child Model


>$comment = Comment::find(1);
>echo $comment->post->title;
Post no 1

S-ar putea să vă placă și