طریقه ساخت فایل CSV در لاراول

۵ اردیبهشت ۱۳۹۶

پکیچ LaraCSV

برای نصب پکیج LaraCSV دستور زیر را اجرا می کنیم:

    composer require "usmanhalalit/laracsv:1.*@dev"
Build CSV

برای ساخت فایل CSV از دستور:

$exporter->build($modelCollection, $fields)
استفاده می کنیم. به مثال زیر توجه کنید:

    $csvExporter->build(User::get(), ['email', 'name', 'created_at']);
Download

برای دانلود فایل CSV از دستور زیر استفاده می کنیم:

    $csvExporter->download();

برای نام دادن به فایل CSVاز دستور زیر استفاده می کنیم:

    $csvExporter->download('active_users.csv');
Advanced Outputs

برای تبدیل خروجی CSV به فایلهای مختلف از دستورات زیر استفاده می کنیم:

    $csv = $csvExporter->getCsv();
    $csv->toHTML(); // To output the CSV as an HTML table
    $csv->jsonSerialize()(); // To turn the CSV in to an array
    $csv = (string) $csv; // To get the CSV as string
    echo $csv; // To print the CSV
Custom Headers

برای تعریف header فایل CSV از دستور زیر استفاده می کنیم:

    $csvExporter->build(User::get(), ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
Modify or Add Values

برای تغییرات در خروجی فایل CSV از فرمان های زیر استفاده می کنیم:

    $csvExporter = new \Laracsv\Export();
    $users = User::get();

    // Register the hook before building
    $csvExporter->beforeEach(function ($user) {
        $user->created_at = date('f', strtotime($user->created_at));
    });

    $csvExporter->build($users, ['email', 'name' => 'Full Name', 'created_at' => 'Joined']);
Add fields and values

برای اضافه کردن فیلدی به فایل CSV از دستورات زیر استفاده می کنیم:

    // The notes field doesn't exist so values for this field will be blank by default
    $csvExporter->beforeEach(function ($user) {
        // Now notes field will have this value
        $user->notes = 'Add your notes';
    });

    $csvExporter->build($users, ['email', 'notes']);
Model Relationships

برای استفاده از relation بین جداول در دیتابیس از دستورات زیر استفاده می کنیم:

    $csvExporter->build($products, ['title', 'category.title']);
    $products = Product::where('order_count', '>', 10)->orderBy('order_count', 'desc')->get();
    $fields = ['id', 'title','original_price' => 'Market Price', 'category_ids',];
    $csvExporter = new \Laracsv\Export();
    $csvExporter->beforeEach(function ($product) {
        $product->category_ids = implode(', ', $product->categories->pluck('id')->toArray());
    });

 نویسنده:حمید شاه محمدی
 تعداد مشاهده خبر:(533)
 هر روز از مقاله های جدید طراحی سایت در کانال تلگرام ما با خبر شوید

 میانگین امتیازات:
 
  تعداد رای دهندگان: {{ count }}
نظرات:

{{ x }}
{{ alert }}

نویسنده:{{ com.name }}
{{ com.body }}
{{ com.created_at }}