PHP code example of muratsplat / multilang

1. Go to this page and download the library: Download muratsplat/multilang library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

muratsplat / multilang example snippets


 'Muratsplat\Multilang\MultilangServiceProvider',

 'MultiLang' =>'Muratsplat\Multilang\Facades\MultiLang',


use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePagesTable extends Migration {

        /**
         * Run the migrations.
         *
         * @return void
         */
         public function up()
         {
            Schema::create('pages', function(Blueprint $t) {

                $t->increments('id');
                $t->boolean('enable')->default(0);
                // you can add more for your needs
                // but don't add columns for multi language
                $t->timestamp('created_at')->nullable();
                $t->timestamp('updated_at')->nullable();    
            
            });
         }
         
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
       
            Schema::drop('pages');
        }

}


use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePageLangsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
            
            Schema::create('pageLangs', function(Blueprint $t) {
            
               $t->increments('id');
               $t->integer('page_id')->unsigned();
               // it is oreign('page_id')->references('id')->on('pages');

               // This reference is optional. If you want to language model
               // to manage app languages, the refrences is recommended.
               // Having a Language model make be easy to manage language
               $t->foreign('__lang_id__')->references('id')->on('languages');

               });
        }

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{       
            Schema::drop('contents');
   
	}

}


use Illuminate\Database\Migrations\Migration;

class languages extends Migration {
    
        
    public function up() {
        
        Schema::create('languages', function($t) {
          

            $t->increments('id');
            $t->string('lang_code', 10);
            $t->string('name', 50);
            $t->string('name_native', 50);
            $t->tinyInteger('enable' )->default(0);
            $t->boolean('default')->default(false);
            $t->timestamps();
            


            $t->index('lang_code');
            $t->unique(array('lang_code', 'name'));
        });
    }
    
    public function down() {
        
        Schema::drop('languages');
    }

    
    
}

// in pageLangs migration class

 $t->foreign('__lang_id__')->references('id')->on('languages');



class DatabaseLanguagesSeeder extends Seeder {
    
    // reference : http://www.loc.gov/standards/iso639-2/php/code_list.php
    // reference : http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes 
    public function run() {
               
         Language::create(array('name' => 'Turkish', 'name_native' => 'Türkçe', 
            'lang_code' => 'tr',  'enable' => 1 , 'default' => 1));

        Language::create(array('name' => 'English', 'name_native' => 'English', 
            'lang_code' => 'en', 'enable' => 1));

        Language::create(array('name' => 'German', 'name_native' => 'Deutsch', 
            'lang_code' => 'de', 'enable' => 1));

        Language::create(array('name' => 'French', 'name_native' => 'Français', 
            'lang_code' => 'fr', 'enable' => 1));

        Language::create(array('name' => 'Russian', 'name_native' => 'русский язык', 
            'lang_code' => 'ru', 'enable' => 1));

        Language::create(array('name' => 'Arabic', 'name_native' => 'العربية', 
            'lang_code' => 'ar', 'enable' => 1));        
    }
}

use Muratsplat\Multilang\Interfaces\MainInterface;
use Muratsplat\Multilang\Traits\MainTrait;

class Page extends \Eloquent implements MainInterface {

    use MainTrait;
    
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'pages';


    protected $fillable = array('enable');
    
        /**
         * Validation Rules
         * 
         * @var array
         */
        public $rules = array(

            'enable'    => '    return $this->PageLangs();
        }
    }

use Muratsplat\Multilang\Interfaces\LangInterface;
use Muratsplat\Multilang\Traits\LangTrait;

class PageLang extends \Eloquent implements LangInterface {

    use LangTrait;
    
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'pageLangs';


    protected $fillable = array('content_id', 'lang_id', 'title', 'content'); 
    
     /**
     * Validation Rules
     * 
     * @var array
     */
    public $rules = array(
            
        'title'        => 'max:100|RequiredForDefaultLang:@,1,Title',
        'content'      => 'max:15000|RequiredForDefaultLang:@,1,Content',      
        
    ); 
      
        /**
         * Defining inversed relation to Content
         * 
         * @return PageLang
         */
        public function Page() {

            return $this->belongsTo('Page', 'id', 'page_id');
        }    

        /**
        * to get Language Models. 
        * use HasMany relationship to access language model
        * 
        * @return  \Illuminate\Database\Eloquent\Relations\HasMany
        */   
        public function mainModel() {

            return $this->Page();
        }
    }

"

  //..page.blade.php
    
    {{Form::open(['action'=>['PageController@store']])}}

        {{Form::text('enable', 'Aktif')}}
    
        @foreach($langs as $v)
        
            {{Form::text("title@$v->id", 'Bir başlık giriniz..')}}
            {{Form::textarea("content@$v->id")}}
            
       @endforeach 
       
    {{Form::close()}}

    
    $rawPost  = array(

            "enable"    => 1,

            'title@1'   => "Foo English",
            'content@1' => "Simple example of content in English",

            'title@2'   => 'Foo Türkçe',
            'content@2' => 'Türkçe bir içerik langur lungur bir yoğurt',

            "title@3"   => 'здравствуйте',
            "content@3" => 'Путинхороший человек. Он любит русские , я думаю, россияне любят его.'      
        );

 


	$rules = ['enable'    => 'dels, it is overwrote on same rule in models. 
    // So one of in model is updated by overwriting
	
    // Rules parameter is optional. 
    // If you have been defined rules in Page model, rules parameter is not need.

    if(MultiLang::create($rawPost, new Page(), $rules)) {
        // it is in success
    } else {
		$instace = MultiLang::getInstance();

		Redirect::route('panel.create')->withErrors($instace)->withInput();
	}

    $wantedLangId = 3;            
    $defaultLangId = 1; // if the value is null or empty, returns PageLang models by Language id
    $wrapper = MultiLang::makeWrapper(Page::find(1), $wantedLangId,$defaultLangId);

    echo $wrapper->title; // returns: "здравствуйте"
    echo $wrapper->content // returns: "Путинхороший человек. Он любит русские , я думаю, россияне любят его."



    $wrapper->wanted(2)->force()->title; // "Foo Türkçe"
    // 99 language id is not existed and so no record is on PageLang Model !
    $wrapper->wanted(99)->force()->title; // null


    private function setMultilangWrapperByEvent($lang_id = 1) {
        
        $events = App::make('events');

        /* setting wanted lang by using event */
        $events->listen('multilang.wrapper.creating',function(MultiLang $event) use($lang_id) {
             
             $event->getWrapperInstance()->setWantedLang($lang_id);
        });
        
    }

bash

 php artisan config:publish muratsplat/multilang