Created
October 15, 2014 16:51
-
-
Save ryanorsinger/74631bf0c8ff6d4c96d4 to your computer and use it in GitHub Desktop.
Image Upload and associating an image to a post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Author
ryanorsinger
commented
Oct 15, 2014
{{ Form::label('title', 'Post Title', array('class' => 'col-sm-2 control-label')) }}
{{ Form::label('body', 'Post Body', array('class' => 'col-sm-2 control-label')) }}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment