首页 > 解决方案 > 从 Laravel 中的 json 响应中删除 ip

问题描述

我在 Laravel 中有 rest api,如下所示:

{
    "id": 17,
    "title": "Devnet",
    "slug": "devnet",
    "content": "sfdf",
    "technology_id": 1,
    "image": "http://127.0.0.1:8000/uploads/posts/1570907475IMG_20171229_123822.jpg|uploads/posts/1570907475IMG_20171229_133927.jpg|uploads/posts/1570907475IMG_20180319_124721.jpg",
    "link": "https://www.somelink.com/in/test/",
    "deleted_at": null,
}

我需要127.0.0.1:8000从所有响应中删除本地 ip () 地址。例如,在图像中我有 3 个文件,但在我提供的代码中,您可以看到 3 个链接,其中只有一个具有完整路径。

实际上在数据库中,他们没有完整的路径。他们都像这样在没有本地 ip 的情况下发布到数据库uploads/posts/image_name.jpg。在模型创建中,我用dd检查了我所有没有本地 ip ( 127.0.0.1:8000) 的图像。只有uploads/posts/image_name.jpg

我如何将数据存储到控制器中的数据库:

    $images = array();
    if ($files = $request->file('image')) {
        foreach ($files as $file) {
            $name =  "uploads/posts/" . time() . $file->getClientOriginalName();
            $file->move("uploads/posts", $name);
            $images[] = $name;
        }
    }

    // validating in here ..
    if I dd($images) in here it show me 3 array of images without local ip.

    $project= Project::create([
        "title" => $request->title,
        "content" => $request->content,
        'image' =>  implode("|", $images),
        "technology_id" => $request->technology_id,
        "slug" => str_slug($request->title),
        "tags" => "required",
        "link" => $request->link
    ]);

还有我的主要Controller返回json查看没什么特别的。

public function index(){
    $result = Project::with('something','something')->get();
    return response()->json($result);
}

项目模型

class Project extends Model
{
    use SoftDeletes;

    protected $fillable = [
        "title","content","image","technology_id","link","slug"
    ];

    public function getImageAttribute($image){
        return asset($image);
    }
    protected $dates = ["deleted_at"];
}

标签: laravellaravel-5.8

解决方案


这个访问器函数是你的罪魁祸首:

public function getImageAttribute($image){
    return asset($image);
}

asset函数返回一个绝对 URL,并且它也不知道如何处理您的内爆图像数组。


推荐阅读