Skip to content

Instantly share code, notes, and snippets.

@ryanorsinger
Created October 15, 2014 16:51
Show Gist options
  • Save ryanorsinger/74631bf0c8ff6d4c96d4 to your computer and use it in GitHub Desktop.
Save ryanorsinger/74631bf0c8ff6d4c96d4 to your computer and use it in GitHub Desktop.
Image Upload and associating an image to a post
@extends('layouts.master')
@section('page-head')
<h1 class="page-header">Create a New Post</h1>
@stop
@section('content')
// Need to add 'files' => true to the attributes array on Form::open
{{ Form::open(array('action' => 'PostsController@store', 'files' => true, 'class' => 'form-horizontal')) }}
{{ Form::label('title', 'Post Title', array('class' => 'col-sm-2 control-label')) }}
{{ Form::text('title', Input::old('title'), array('class' => 'form-control')) }}
{{ Form::label('body', 'Post Body', array('class' => 'col-sm-2 control-label')) }}
{{ Form::textarea('body', Input::old('body'), array('rows' => '10', 'class' => 'form-control')) }}
{{ Form::label('image','File', array('class'=>'col-sm-2 control-label')) }}
{{ Form::file('image','',array('class'=>'form-control')) }}
{{ Form::close() }}
@stop
public function store()
{
$validator = Validator::make(Input::all(), Post::$rules);
if ($validator->fails()) {
Session::flash('errorMessage', 'Failed to save post!');
return Redirect::back()->withInput()->withErrors($validator);
} else {
$post = new Post();
$post->user_id = Auth::id();
if (Input::hasFile('image')) {
$file = Input::file('image');
$destination_path = public_path() . '/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destination_path, $filename);
$post->image = '/img/' . $filename;
}
$post->title = Input::get('title');
$post->body = Input::get('body');
$post->save();
Session::flash('successMessage', 'Post saved!');
return Redirect::action('PostsController@show', $post->id);
}
}
@ryanorsinger
Copy link
Author

{{ Form::label('title', 'Post Title', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
    {{ Form::text('title', Input::old('title'), array('class' => 'form-control')) }}
    
    @foreach ($errors->get('title') as $message)
        <p class="help-block">{{{ $message }}}</p>
    @endforeach
</div>
{{ Form::label('body', 'Post Body', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
    {{ Form::textarea('body', Input::old('body'), array('rows' => '10', 'class' => 'form-control')) }}
    
    @foreach ($errors->get('body') as $message)
        <p class="help-block">{{{ $message }}}</p>
    @endforeach
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment