简体   繁体   English

如果在Laravel 4中已删除用户,如何删除用户徽标?

[英]How to delete user's logo if user has been deleted in Laravel 4?

DESCRIPTION 描述

I have a field in my database called: logo_path in my users table. 我的用户表中的数据库中有一个字段: logo_path logo_path will only store a path to a logo. logo_path将仅存储徽标的路径 I also have a logo_path folder in my app/files/logo_path/ 我的app / files / logo_path /中也有一个logo_path文件夹

I have a create user form, when creating a user, I allow a user to upload their desire avatar/logo. 我有一个创建用户表单,在创建用户时,我允许用户上传其所需的头像/徽标。

WORK 工作

The process of creating an account is work, the upload is also work, the file is also save to where I wanted. 创建帐户的过程正常,上传也正常,文件也保存到我想要的位置。

PROBLEM 问题

Here comes one small problem, I have a lot of randoms photo in my logo_path folder now. 这是一个小问题,我的logo_path文件夹中现在有很多随机照片。 All of them is getting annoying, I was wondering if there is there a way to delete it's logo of that user if the user has been deleted ? 所有这些都变得烦人,我想知道是否有一种方法可以删除该用户的徽标(如果该用户已被删除)?

UserController --> destroy() UserController-> destroy()

public function destroy($id){

    $user = User::find($id);
    $user->delete();

    return Redirect::to('/users/');

}

Often, something like this can happen in more than one place. 通常,类似的事情可能会发生在多个地方。 Rather than catching them all in the controller, Laravel's model events can let you do this in one place reliably. Laravel的模型事件可以让您可靠地在一处执行此操作,而不是将它们全部捕获在控制器中。

http://laravel.com/docs/4.2/eloquent#model-events http://laravel.com/docs/4.2/eloquent#model-events

class User extends Eloquent {
    public static function boot() {
        parent::boot();

        User::deleted(function($user) {
            // now that the user has been deleted, delete their logo
            File::delete('path/to/logos/' . $user->logo);
        }
    }

}

Just add 只需添加

$success = File::delete(base_path().'/app/files/logo_path/'.$user->logo_path);

UPDATED : UserController 更新 :UserController

public function destroy($id){

    $user = User::find($id);
    $user->delete();
    $success = File::delete(base_path().'/app/files/logo_path/'.$user->logo_path);

    return Redirect::to('/users/');

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM