Tag Archive Laravel 5

Byphunsanit

laravel ajax method delete

เขียน ui laravel 5.1 อยู่ แบบใช้ ajax update ข้อมูล โดยเดิมมันใช้ form ธรรมดาแต่ใช้ method เป็น DELETE ทดลองส่งคำสั่งผ่าน ajax อยู่นานก็ไม่ได้ผล แถมมันวิ่งไปที่อื่นอีกตะหาก ทดลองเขียน php ธรรมดามาลองดูก็ไม่เจออะไร

นั่งงงอยู่นาน ก็ pass ค่าไปถูก เขียน php ธรรมดาไป ก็ได้ค่าไปถูก จน search ไปเจอ Delete request Jquery Ajax doesn’t work ที่แท้ laravel ถ้าจะใช้ method delete ต้องใช้ “method”: “POST” กับตัวแปร “_method”: “delete”

    $('.glyphicon-trash').click(function(e) {
        e.preventDefault();

        var r = confirm('Are you sure?');
        if(r == true) {
            $.ajax({
                "data": {
                    "_method":"DELETE",
                    "_token": "{{ csrf_token() }}",
                    },
                "success": function(result) {
                    location.reload();
                   alert('success');
                },
                "type": "POST",
                "url": "/admin/index",
            });
        }
    });

ใช้ได้แล้ว แต่น่าจะเขียนเป็นคู่มือเอาไว้นะ

Byphunsanit

CRUD ใน laravel 5

บอกเลย CRUD (Create, read, update and delete generator) ใน laravel 5 หายากมากจน GII ของ YII ดูเทพขึ้นมาทันที ตัวที่พอจะเทียบได้ก็มี Laravel Generator

ติดตั้งโดย

  1. เพิ่ม package InfyOmLabs/laravel-generator ในไฟล์ composer.json
      "require": {
      ...
      "infyomlabs/adminlte-templates": "dev-master",
      "infyomlabs/generator-builder": "dev-master",
      "infyomlabs/laravel-generator": "dev-master",
      "infyomlabs/swagger-generator": "dev-master",
      "jlapp/swaggervel": "dev-master"
      "laravelcollective/html": "5.2.*"
      ...
      },
      
  2. run command
    composer update
  3. เปิดไฟล์ \config\app.php เพิ่ม
      ...
      'providers' => [
      ...
      \InfyOm\Generator\InfyOmGeneratorServiceProvider::class,
      \InfyOm\GeneratorBuilder\GeneratorBuilderServiceProvider::class,
      Collective\Html\HtmlServiceProvider::class,
      Laracasts\Flash\FlashServiceProvider::class,
      Prettus\Repository\Providers\RepositoryServiceProvider::class,
      ...
      ],
    
      'aliases' => [
    
      'Flash'     => Laracasts\Flash\Flash::class,
      'Form'      => Collective\Html\FormFacade::class,
      'Html'      => Collective\Html\HtmlFacade::class,
    
      ],
  4. Publish ไฟล์ไปโฟลเดอร์ public โดย run command
    php artisan vendor:publish
    php artisan infyom:publish
  5. Run routes Publish Command
    php artisan infyom.publish:generator-builder

    จะเพิ่ม rute

    Route::get('generator_builder', '\InfyOm\GeneratorBuilder\Controllers\GeneratorBuilderController@builder');
    Route::get('field_template', '\InfyOm\GeneratorBuilder\Controllers\GeneratorBuilderController@fieldTemplate');
    Route::post('generator_builder/generate', '\InfyOm\GeneratorBuilder\Controllers\GeneratorBuilderController@generate');
  6. Publish view โดย run command
    php artisan infyom.publish:generator-builder --views
  7. เปิดไฟล์ \config\infyom\generator_builder.php แก้เป็น
    <?php
    
    return [
    
        'views' => [
    
            'builder' => 'infyom.generator-builder.builder',
    
            'field-template' => 'infyom.generator-builder.field-template'
        ]
    ];
  8. เปิดไฟล์ \config\infyom\laravel_generator.php แก้ ‘templates’ => ‘core-templates’, เป็น ‘templates’ => ‘adminlte-templates’,

ทดลองใช้

  1. ทดลองเรียกดู http://localhost/…/generator_builder
  2. แต่กรอกอะไรก็เจอ error Fail!result ลองจับ traffic ดูก็เห็นว่ามี error MethodNotAllowedHttpException in RouteCollection.php line 218: เปิดไฟล์ \resources\views\infyom\generator-builde\builder.blade.php บรรทัด 321 แก้ type: “POST” เป็น method: “POST”,
Byphunsanit

สร้าง backend ใน laravel 5

ข้ามไปอ่าน Laravel: AdminLTE จะอัพเดตกว่า

ผมเลือก AdminLTE มาใช้เป็น backend เพราะว่าเขียนโดยใช้ bootstrapt สวยพอประมาณ มีตัวอย่างเยอะ และที่สำคัญแจกฟรี และคุณ Sergi Tur Badenas แปลงให้ใช้กับ laravel 5 ไว้ให้เรียบร้อยแล้ว (framework อื่นก็มีครับ ตาม link ผมก็ใช้ใน YII2 อยู่เหมือนกัน)

ติดตั้งโดย

  1. เพิ่ม package acacha/adminlte-laravel ในไฟล์ composer.json
        "require": {
        ...
        "acacha/admin-lte-template-laravel": "2.*"
        ...
        },
  2. run command
    composer update
  3. เปิดไฟล์ \config\app.php เพิ่ม
        ...
        'providers' => [
        ...
        Acacha\AdminLTETemplateLaravel\Providers\AdminLTETemplateServiceProvider::class,
        App\Providers\RouteServiceProvider::class
        ...
        ],
    
        'aliases' => [
    
        'AdminLTE' => Acacha\AdminLTETemplateLaravel\Facades\AdminLTE::class,
    
        ],
  4. Publish ไฟล์ไปโฟลเดอร์ public โดย run command
    php artisan vendor:publish --tag=adminlte --force

สร้าง backend

  1. สร้างไฟล์ \app\Http\Controllers\AdminController.php
    <?php
    
    namespace App\Http\Controllers;
    
    use App\User;
    use App\Http\Controllers\Controller;
    
    class AdminController extends Controller {
    
        /**
         * Show the profile for the given user.
         */
        public function index()
        {
        	return view('home');
        }
    
    }
    
  2. เพิ่ม route ในไฟล์ \app\Http\routes.php
    ...
    Route::get('admin/', 'AdminController@index');
    ...
    
Byphunsanit

สร้าง muti site ใน laravel

ต้องการสร้างเว็บรองรับหลายๆ บริษัท โดยที่ใช้ code ชุดเดียวกันและให้ฝ่ายที่ดูแลสามารถเพิ่มข้อมูลและเว็บไซต์ ได้เองโดยที่ไม่ต้องใช้ความรู้ทางด้านการเขียนโปรแกรมเลย

เจอ package ชื่อ delatbabel/site-config แต่เพราะว่าเค้ารองรับแค่ laravel 5.1 เลยต้องสร้าง project ใหม่ตั้งแต่ต้นเลย

  1. พิมพ์ command
    composer create-project laravel/laravel sites "5.1.*"
  2. แก้ config ในไฟล์ .env ให้ติดต่อ databse ได้
    ...
        DB_CONNECTION=mysql
        DB_HOST=127.0.0.1
        DB_DATABASE=sites
        DB_USERNAME=root
        DB_PASSWORD=xxx
    ...
  3. เพิ่ม package ในไฟล์ composer.json
    ...
        "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
    ...
        "delatbabel/site-config": "~1.0"
        },
    ...
  4. run command
        composer update
        
  5. เปิดไฟล์ config\app.php เพิ่ม
    ...
        'providers' => [
    ...
        Delatbabel\SiteConfig\SiteConfigServiceProvider::class,
    ...
        ],
    ...
        'aliases' => [
    
        'SiteConfigSaver'   => Delatbabel\SiteConfig\Facades\SiteConfigSaver::class,
    
        ],
    ...
  6. เพิ่ม Boostrap the Config Loader ใน 2 ไฟล์ คือ \app\Console\Kernel.php และ \app\Http\Kernel.php ต้องครบ 2 ไฟล์นะครับ ผมใส่ไม่ครบงงอยู่นานมากทำไม่มันมันใช้ไม่ได้
    ...
        protected function bootstrappers()
        {
            $bootstrappers = parent::bootstrappers();
    
            // Add the SiteConfig bootstrapper to the end.
            $bootstrappers[] = 'Delatbabel\SiteConfig\Bootstrap\LoadConfiguration';
    
            return $bootstrappers;
        }
    ...
  7. Incorporate and Run the Migrations โดย run command
        php artisan vendor:publish --tag=migrations --force
        php artisan migrate

การติดตั้งเสร็จแล้ว ที่นี้จะทดลองใช้งาน

  1. สร้างไฟล์ \app\Http\Controllers\HomeController.php
      <?php
    
    namespace App\Http\Controllers;
    
    use App\User;
    use App\Http\Controllers\Controller;
    
    class HomeController extends Controller {
    
        /**
         * Show the profile for the given user.
         */
        public function index()
        {
    
            return 'title = '.config('config.title');
    
            $config = config()->all();
    
            return '<pre>'. print_r($config ,true).'</pre>';
        }
    
    }
    
  2. เพิ่ม route ในไฟล์ \app\Http\routes.php
    ...
    Route::get('/', 'HomeController@index');
    ...
    
  3. ทดลอง set domain ขึ้นมาเทส เปิดไฟล์ C:\Windows\System32\drivers\etc\hosts
    ...
    127.0.0.1	phunsanit.com
    127.0.0.1	pitt.com
    ...
    
  4. เพิ่มข้อมูลทกสอบโดยใช้
    INSERT INTO `configs` (`id`, `website_id`, `environment`, `group`, `key`, `value`, `type`, `created_at`, `updated_at`) VALUES
    (1, 1, NULL, 'config', 'title', 'localhost', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
    (2, 1, 'prod', 'config', 'title', 'localhost ON production', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
    (3, 1, 'test', 'config', 'title', 'localhost IN TEST SERVER', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
    (4, 2, NULL, 'config', 'title', 'pitt.com', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
    (5, 2, 'prod', 'config', 'title', 'pitt.com ON production', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00'),
    (6, 2, 'test', 'config', 'title', 'pitt.com IN TEST SERVER', '', '0000-00-00 00:00:00', '0000-00-00 00:00:00');
    
    INSERT INTO `websites` (`id`, `name`, `http_host`, `environment`, `created_by`, `updated_by`, `created_at`, `updated_at`, `deleted_at`) VALUES
    (1, 'prototype', 'localhost', 'test', NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL),
    (2, 'prototype', 'pitt.com', 'test', NULL, NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00', NULL);
    
  5. ทดสอบโดยเปิด http://localhost/mcms/public/ และ http://pitt.com/mcms/public/

นำไปดัดแปลงให้เหมาะกับงานที่ทำครับ

Byphunsanit

สร้าง grid ใน laravel แบบ advance

การใช้ Nayjest Grids แบบ advance เพื่อที่จะสามารถค้นหา filter ข้อมูล, export ไฟล์ ออกมาในรูปแบบ .csv และ excel ได้

ติดตั้งโดย

  1. เปิดไฟล์ composer.json เพิ่ม
    ...
            "laravelcollective/html": "^5",
            "maatwebsite/excel": "~2.1.0",
            "nayjest/grids": "^1.3.1"
    ...
    
  2. Command
    composer update
  3. เปิดไฟล์ \config\app.php เพิ่ม
        'providers' => [
    ...
            'Collective&#92;Html&#92;HtmlServiceProvider',
            'Maatwebsite&#92;Excel&#92;ExcelServiceProvider',
            'Nayjest&#92;Grids&#92;ServiceProvider',
    ...
    
        'aliases' => [
    ...
            'Excel' => 'Maatwebsite&#92;Excel&#92;Facades&#92;Excel',
            'Form' => 'Collective&#92;Html&#92;FormFacade',
            'Grids' => 'Nayjest&#92;Grids&#92;Grids',
            'HTML' => 'Collective&#92;Html&#92;HtmlFacade',
            'Input' => 'Illuminate&#92;Support&#92;Facades&#92;Input',
    ...
    ]

สร้าง grid โดย

  1. <?php
    
    namespace App\Http\Controllers;
    
    use App\user;
    use HTML;
    use Nayjest\Grids\Components\Base\RenderableRegistry;
    use Nayjest\Grids\Components\ColumnHeadersRow;
    use Nayjest\Grids\Components\ColumnsHider;
    use Nayjest\Grids\Components\CsvExport;
    use Nayjest\Grids\Components\ExcelExport;
    use Nayjest\Grids\Components\FiltersRow;
    use Nayjest\Grids\Components\Filters\DateRangePicker;
    use Nayjest\Grids\Components\HtmlTag;
    use Nayjest\Grids\Components\Laravel5\Pager;
    use Nayjest\Grids\Components\OneCellRow;
    use Nayjest\Grids\Components\RecordsPerPage;
    use Nayjest\Grids\Components\RenderFunc;
    use Nayjest\Grids\Components\ShowingRecords;
    use Nayjest\Grids\Components\TFoot;
    use Nayjest\Grids\Components\THead;
    use Nayjest\Grids\EloquentDataProvider;
    use Nayjest\Grids\FieldConfig;
    use Nayjest\Grids\FilterConfig;
    use Nayjest\Grids\Grid;
    use Nayjest\Grids\GridConfig;
    
    class UsersController extends Controller
    {
    
        public function Index()
        {
    
            $query = (new User)
                ->query();
    
            $grid = new Grid(
                (new GridConfig)
                    ->setDataProvider(
                        new EloquentDataProvider($query)
                    )
                    ->setName('UserIndex') /* grid unque id */
                    ->setPageSize(20)
                    ->setColumns([
                        (new FieldConfig)
                            ->addFilter(
                                (new FilterConfig)
                                    ->setOperator(FilterConfig::OPERATOR_LIKE)
                            )
                            ->setLabel('ID')
                            ->setName('id') /* field */
                            ->setSortable(true)
                            ->setSorting(Grid::SORT_DESC)
                        ,
                        (new FieldConfig)
                            ->addFilter(
                                (new FilterConfig)
                                    ->setOperator(FilterConfig::OPERATOR_LIKE)
                            )
                            ->setLabel('Name')
                            ->setName('name')
                            ->setSortable(true)
                        ,
                        (new FieldConfig)
                            ->addFilter(
                                (new FilterConfig)
                                    ->setOperator(FilterConfig::OPERATOR_LIKE)
                            )
                            ->setLabel('Email')
                            ->setName('email')
                            ->setSortable(true)
                        ,
                        (new FieldConfig)
                            ->addFilter(
                                (new FilterConfig)
                                    ->setOperator(FilterConfig::OPERATOR_LIKE)
                            )
                            ->setLabel('Update Information')
                            ->setName('count_update')
                            ->setSortable(true)
                        ,
                        (new FieldConfig)
                            ->setLabel('Created')
                            ->setName('created_at')
                            ->setSortable(true)
                        ,
                        (new FieldConfig)
                            ->setLabel('Last Update')
                            ->setName('updated_at')
                            ->setSortable(true),
                    ])
                    ->setComponents([
                        (new THead)
                            ->setComponents([
                                (new ColumnHeadersRow),
                                (new FiltersRow)
                                    ->addComponents([
                                        (new RenderFunc(function () {
                                            return HTML::style('js/daterangepicker/daterangepicker-bs3.css')
                                            . HTML::script('js/moment/moment-with-locales.js')
                                            . HTML::script('js/daterangepicker/daterangepicker.js')
                                                . "<style>
                                                    .daterangepicker td.available.active,
                                                    .daterangepicker li.active,
                                                    .daterangepicker li:hover {
                                                        color:black !important;
                                                        font-weight: bold;
                                                    }
                                               </style>";
                                        }))
                                            ->setRenderSection('filters_row_column_created_at'),
                                        (new DateRangePicker)
                                            ->setName('created_at')
                                            ->setRenderSection('filters_row_column_created_at')
                                            ->setDefaultValue(['1990-01-01', date('Y-m-d H:i:s')]),
                                        (new DateRangePicker)
                                            ->setName('created_at')
                                            ->setRenderSection('filters_row_column_updated_at')
                                            ->setDefaultValue(['1990-01-01', date('Y-m-d H:i:s')]),
                                    ])
                                ,
                                (new OneCellRow)
                                    ->setRenderSection(RenderableRegistry::SECTION_END)
                                    ->setComponents([
                                        new RecordsPerPage,
                                        new ColumnsHider,
                                        (new CsvExport)
                                            ->setFileName('usersExport_' . date('Y-m-d'))
                                        ,
                                        (new ExcelExport())
                                            ->setFileName('usersExport_' . date('Y-m-d'))
                                        ,
                                        (new HtmlTag)
                                            ->setContent('<span class="glyphicon glyphicon-refresh"></span> Filter')
                                            ->setTagName('button')
                                            ->setRenderSection(RenderableRegistry::SECTION_END)
                                            ->setAttributes([
                                                'class' => 'btn btn-success btn-sm',
                                            ]),
                                    ]),
                            ])
                        ,
                        (new TFoot)
                            ->setComponents([
                                (new OneCellRow)
                                    ->setComponents([
                                        new Pager,
                                        (new HtmlTag)
                                            ->setAttributes(['class' => 'pull-right'])
                                            ->addComponent(new ShowingRecords)
                                        ,
                                    ]),
                            ])
                        ,
                    ])
            );
            $grid = $grid->render();
    
            return view('users.index', [
                'grid' => $grid,
            ]);
        }
    
    }
    
  2. สร้าง view \resources\views\users\index.blade.php
    @extends('layouts.app')
    
    @section('title', 'Users')
    
    @section('main-content') <a href="{{ url('/excels/form') }}">
    <button class="btn btn-success btn-sm"><span class="glyphicon glyphicon-upload"></span> Import Datas</button>
    </a> @if(!empty($text))
    <div class="container">{!! $text !!}</div>
    @endif
    <?=$grid;?>
    @stop
  3. สร้าง route โดยไปที่ \app\Http\routes.php
    ...
    Route::get('/users/index', 'UsersController@index');
    ...

ทดลองโดยเรียก /users/index ในเครื่องผมคือ http://localhost/laravel52/public/users/index grid แสดงข้อมูลออกมาแล้วแต่ จะส่งออกเป็นไฟล์ csv หรือ excel ยังไงละ ใจเย็นๆครับ อ่าน สร้าง grid ใน laravel แบบ advance ครับ