I have this database
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 100) -> nullable();
$table->text('content', 300)-> nullable();
$table->string('image', 100)-> nullable();
$table->string('phone', 300)-> nullable();
$table->string('coordinates', 300)-> nullable();
$table->string('website', 300)-> nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post');
}
};
i want to post and get the image, the only thing that i confuse is, how to get the image that i post, im already call it in my API but the result is 404, im already uploaded it on web service http://lovemonster.my.id/hospital just look & click on image section, it showing the error, this is my controller:
class HospitalController extends Controller
{
public function create(Request $request)
{
$data = $request->all();
$hospital = Hospital::create($data);
return response()->json($hospital);
}
public function index()
{
$hospital = Hospital::all();
return response()->json($hospital);
}
}
and this is my model:
class Hospital extends Model
{
protected $table = 'post';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title','content','image', 'phone', 'coordinates', 'website'
];
}
how to get the image that i store, what the code looks like on my controller, if you know how to do it please let me know cause im new to lumen and laravel
For post requests, you need to save image inside public or storage folder and add that path inside db for image.
class HospitalController extends Controller
{
public function create(Request $request)
{
// upload image
$filename = $this->getFileName($request->image);
$request->image->move(base_path('public/images'), $filename);
$hospital = new Hospital(request()->except('image'));
$hospital->image = $filename;
$hospital->save();
return response()->json($hospital);
}
protected function getFileName($file)
{
return str_random(32) . '.' . $file->extension();
}
public function index()
{
$hospital = Hospital::all();
return response()->json($hospital);
}
}
Your model Hospital.php
class Hospital extends Model
{
protected $table = 'post';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title','content','image', 'phone', 'coordinates', 'website'
];
// this function will give your full image URL in records
public function getImageAttribute($value)
{
return env('APP_URL').$value;
}
}
And in .env set APP_URL with your domain name of project
like https://www.project.com/