niedziela, 25 maja 2014

CKEditor image upload with Laravel

CKEditor default doesn't have a possibility to upload a photo, it's obvious because he doesn't have an idea on which place you want to save it. Even if he will know he doesn't know how to save it.

To allow you to upload an image you must write two things:
  1. post upload action in your controller
  2. CKEditor replace for property filebrowserUploadUrl
Writing upload action is easy it's only should contain
  • checking if uploaded file is really image 
  • saving file in your chosen destiny
  • optionally save to database information where file had been saved and to what structure it was connected
  • return statement must send URL of uploaded image
It can look like this:
public function postUploadToArt($article)
        $input = Input::all();

        $rules = array(
            'upload' => 'image|max:15000|required',

        $validation = Validator::make($input, $rules);

        if ($validation->fails())
            return Response::make($validation->messages(), 400);

        $file = Input::file('upload');
        $article->gallery->addPhoto($file); //saving file to server and path to DB
        return URL::to($article->gallery->path.'/'.$file->getClientOriginalName());

Replacing CKEditor property should be also not very hard because its only need to start your editor by this code:
CKEDITOR.replace( 'editor1', {
        filebrowserUploadUrl: '{{URL::action("AdminArticlesController@postUploadToArt",$article->id)'}}

Nah that's code is wrong? You must remember to send with you post a request also csrf token! Like that:
var csrf = '{{csrf_token()}}' ;

CKEDITOR.replace( 'editor1', {
        filebrowserUploadUrl: '{{URL::action("AdminArticlesController@postUploadToArt",$article->id)}}?csrf_token='+csrf


2 komentarze: