How to Create a Blog in YII2

Hi Guys,

First Install composer (click here) If you already installed leave it.

Download basic Yii2 Template and follow below commands for user migrations.

composer create-project nenad/yii2-basic-template blog

Create a sample database and give the credentials at blog/_protected/config/db.php.

Run below migration commands for user access.

cd blog/_protected

./yii migrate

./yii rbac/init

Then Create a table in the database.

CREATE TABLE `posts` (
`id` int(11) NOT NULL,
`date_time` datetime NOT NULL,
`title` varchar(60) NOT NULL,
`post` text NOT NULL,
`image` varchar(150) NOT NULL,
`status` enum(‘active’,’inactive’,’draft’) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `posts`
ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);

Create Model and CRUD for posts at http://localhost/blog/gii

Install any Text editor (I used CKEDITOR).

composer require 2amigos/yii2-ckeditor-widget

Then Create a model/UploadForm.php for upload files to the uploads folder.


Then Add/Edit views/posts/_form.php
cd2
Replace Create functionality in PostsController.php
use app\models\UploadForm;

use yii\web\UploadedFile;
public function actionCreate()

    {

        $model = new Posts();

        if ($model->load(Yii::$app->request->post())) {

            $m = new UploadForm();

            $m->file = UploadedFile::getInstance($model, 'image');

            $file_name = '';

            if ($m->file && $m->validate()) {                

                $file_name = 'uploads/' . $m->file->baseName . '.' . $m->file->extension;

                $m->file->saveAs($file_name);

            }

            $model->image = $file_name;

            if($model->validate() && $model->save()){

                return $this->redirect(['view', 'id' => $model->id]);

            }

        }
Replace below code in views/site/index.php
cd.PNG

Add the below code in views/posts/view.php
cd1
Git Link: Git

3 thoughts on “How to Create a Blog in YII2

  1. dear Sir
    The project createing on yii2 basic version ?
    The program code can direacte downlaod ?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: