Search code examples
phpmysqllaravelbackup

How to take backup of partial data in Laravel?


I am working on a project in Laravel where I have to take backup of the database (mySQL).

I have learned to take backup of entire database or selected tables. But the challenge for me is to take backup of only some rows.

Here is the scenario:

There are 4 tables

  • users
  • posts
  • tags
  • post_tag

Their relations

  • user hasMany posts and each post belongsTo a user
  • post hasMany Tags and a Tag hasMany posts

If if initiate backup of a user (where userId = 1), Then I should get a backup file containing all the four tables mentioned above with data related to userId = 1.

Also, how to restore the data?

Updates

It is a role based application. (There are 2 roles editor and author)

Editor has the privilege to backup and restore data of author.


Solution

  • If this is an server admin only operation, you may use iseed to generate seeding files from your existing data in database. The restoration would be easy through Laravel's database seeding.

    If this is a user operation, then you would probably need to program your own import / export feature. You may use a combination of fopen('php://output') with fputcsv for the database to csv export. Then you may reference some available tutorials to write the csv to database import with Eloquent.