laravelresteloquentlaravel-7laravel-response

Laravel rest api, get the full link of the images associated with the data in database stored in uploads/posts


I am working on the Laravel project project and came across a problem. I would like my function on my ApiController.php to bring me the full links of the images from the POST table, store in uploads / posts. so i tried this method, how can i get this result?

//ApiController
    <?php
    namespace App\Http\Controllers;
    use Illuminate\Support\Arr;
    use Illuminate\Http\Request;
    use Illuminate\Support\Str;
    use Carbon\Carbon;
    use App\Category;
    use App\Post;
    
    class ApiController extends Controller
    {
        //
        public function getposts(){
            $post = Post::select('post_title','post_content','category_id','image')
                        ->with('category')
                        ->get();
            $categories=Category::all();
            return response()->json($post, 200, [], JSON_UNESCAPED_UNICODE);
    }
    }

The result that i get

Api Result
    [
        {
            "post_title": "post title 1",
            "post_content": "<p>content</p>",
            "category_id": "1",
            "image": "uploads/posts/image1.png",
            "category": {
                "id": 1,
                "name": "category1",
            }
        },
    ]

so how to get the full link of the image? //https://www.mylink.com/uploads/posts/image1.png the result i want to show

//result i want
[
            {
                "post_title": "post title 1",
                "post_content": "<p>content</p>",
                "category_id": "1",
                "image": "https://www.mylink.com/uploads/posts/image1.png",
                "category": {
                    "id": 1,
                    "name": "category1",
                }
            },
        ]

Solution

  • You can simply foreach all items, like this:

    foreach ($post as $p) {
       $p->image = url($p->image);
    }
    

    Or more elegant way - you can concat image data directly in the query:

    Post::select('post_title','post_content','category_id', \DB::raw('CONCAT("'.url('/').'/", image) as image'))->get();