The code below will store a base64 image on another website and create an event to display the image on a Vue page in real time. It works fine and all.
My question is, is this a good way of doing it or there's a better way to structure the code? I've thought about placing the logic in a listener but it doesn't seem that I need to use one. For queues, I'll add them later on.
Controller
public function store(Request $request)
{
$base64 = $request->image;
$image = str_replace('data:image/png;base64,', '', $base64);
$imageName = 'draw'.time().'.png';
$response = $this->guzzleClient()->post(config('archiving.api_postBase64_file'),
[
'multipart' => [
[
'name' => 'file',
'contents' => $image
],
[
'name' => 'file_name',
'contents' => $imageName
],
[
'name' => 'file_folder',
'contents' => 'drawings'
],
],
]
);
if($response->getStatusCode() >= 500){
return response($response->getBody(), $response->getStatusCode());
}else{
$drawing = Drawing::create([
'user_id'=>Auth::id(),
'file_name'=>$imageName,
]);
event(new NewDrawing($drawing));
return response('Drawing created!',200);
}
}
NewDrawing Event
class NewDrawing implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $drawing;
public function __construct(Drawing $drawing)
{
$this->drawing = $drawing;
}
public function broadcastOn()
{
return new Channel('channel-drawing');
}
}
Frontend (Vue)
<script>
export default {
data(){
return{
images:'',
}
},
methods:{
listen() {
Echo.channel('channel-drawing')
.listen('NewDrawing', res => {
this.images.push(res.drawing);
})
}
},
mounted() {
this.listen()
}
}
</script>