Laravel 5.4 image gallery - php

I am building a Laravel web application where I need a dynamic image gallery, I build a backend admin panel where I can add images, I succeed to add and save the images to the database but I can not edit or delete them.
The error is:
ErrorException in UrlGenerationException.php line 17: Missing required parameters for [Route: galleries.update] [URI:
backend/galleries/{gallery}]. (View: /var/www/html/tryout101/resources/views/backend/gallery/edit.blade.php)
This my route code:
<?php
/*backend access*/
Route::group(['prefix' => '/backend'], function() {
/*The route Dashboard main page */
Route::get('/' , 'AdminController#index')->name('dashboard');
Route::resource('galleries' , 'GalleriesController');
});
This the Controller code:
<?php
namespace App\Http\Controllers;
use App\Gallery;
use Illuminate\Http\Request;
use Image;
use Illuminate\Support\Facades\Input;
class GalleriesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$gallery = Gallery::all();
return view('backend.gallery.library', compact('gallery'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.gallery.uploadform');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$gallery = new Gallery();
$this->validate($request, [
'title' => 'required',
'image' => 'required'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = time(). '-' .$file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'/images/', $filename);
}
$gallery->save();
return $this->create()->with('success', 'Image Uploaded
Successfully');
}
/**
* Display the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function show(Gallery $gallery)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function edit(Gallery $gallery)
{
if(!$gallery){
return redirect('dashboard')->with(['fail'=>'post not found']);
}
return view('backend.gallery.edit',compact('gallery'));
}
public function update(Request $request, Gallery $gallery)
{
$this->validate($request, [
'title'=>'required|max:120',
'image'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = $file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'images/', $filename);
}
$gallery->update();
return Redirect()->route('dashboard')->with(['success'=> 'post
successfully updated']);
}
public function destroy(Gallery $gallery)
{
//
}
}
/This is my edit page/
#extends('layouts.backend-master')
#section('styles')
<link rel="stylesheet" href="">
#endsection
#section('content')
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1>File Upload</h1>
<form action="{{route('galleries.update')}}" method="post"
enctype="multipart/form-data">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title"/>
</div>
<div class="input-group">
<label for="description">Description</label>
<textarea type="text" name="description" id="description" rows="8">
</textarea>
</div>
<div class="input-group">
<label for="image">Select image to upload:</label>
<input type="file" name="image" id="file">
</div>
<button type="submit" class="btn">Update</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
<input type="hidden" name="gallery" value="{{$gallery->id}}">
</form>
#endsection
#section('scripts')
#endsection

The fact is that the route 'galleries.update' requires a Gallery
Therefore, you should give him which Gallery you want to go to when calling the route function with that route
Thus, I think that changing
route('galleries.update')
into
route('galleries.update', $gallery)
will make everything fine

Related

Property [title] does not exist on the Eloquent builder instance, PHP LARAVEL

This type of question has been asked before but not one addresses my particular query. I have tried all the solutions but non seem to work.
I am building a Blog with Laravel and this particular error occurs when I try to edit any of my posts. You are all encouraged to participate. thank you.
edit.blade.php
#extends('layouts.app')
#section('content')
#if(count($errors)>0)
<ul class="list-group">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<div class="panel panel-default">
<div class="panel-heading">
Edit post{{$post->title}}
</div>
<div class="panel-body">
<form action="{{ route('post.update', ['id'=>$post->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for="featured">Featured Image</label>
<input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select type="file" name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control" >{{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit">Update Post</button>
</div>
</div>
</form>
</div>
</div>
#stop
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Category;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.posts.index')->with('posts', Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$categories =Category::all();
if ($categories-> count()==0){
Session::flash('info', 'You must have some categories before attempting to create a post');
return redirect()->back();
}
return view('admin.posts.create')->with('categories', Category::all());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title'=> 'required|max:255',
'featured'=>'required|image',
'content'=>'required',
'category_id' => 'required'
]);
$featured=$request->featured;
$featured_new_name= time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post=Post::create([
'title'=> $request->title,
'content'=> $request->content,
'featured'=> 'uploads/posts/' .$featured_new_name,
'category_id'=> $request->category_id,
'slug' => Str::slug($request->title)
]);
Session::flash('success', 'Post created Successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post=Post::find($id);
return view('admin.posts.edit')->with('post', Post::find($id)->with('categories', Category::all()));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$post =Post::find($id);
$this->validate($request, [
'title'=> 'required',
'content'=>'required',
'category_id'=>'required']
);
if($request->hasfile('featured')){
$featured=$request->featured;
$featured_new_name=time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name );
$post->featured=$featured_new_name;
}
$post->title=$request->title;
$post->content=$request->content;
$post->category_id=$request->category_id;
$post->save();
Session::flash('success', 'Your post was just updated.');
return redirect()->route('posts');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post =Post::find($id);
$post->delete();
Session::flash('success', 'Your post was just Trashed.');
return redirect()->back();
}
}
Property [title] does not exist on the Eloquent builder instance
This error message is telling you that you are trying to load a property named 'title' on an entity of type 'Eloquent builder'.
Eloquent builder is the type of object which can be used to query the database. The results of a call to ->first() on an Eloquent builder instance would be a Property entity, which is likely what you want.
Please examine and share the code where the Property is being loaded from the database. Do you do something, such as ->first(), to execute the query?

Undefined variable when using error is coming

I have made a simple form when I am calling the form from api route it is showing an error that "errors" is an undefined variable when I am calling using web route it just works fine and shows no error. Why is this happening? Since error is a pre defined variable but why is it showing error.
Layout file:
#extends('layout')
#section('content')
<h1 class="title">Simple Form</h1>
<form method="POST" action="/website/atg/public/projects">
#csrf
<div class="field">
<label class="label" for="name">Name</label>
<div class="control">
<input type="text" class="input" name="name" placeholder="Enter Name" value="{{old('name')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="email">E-mail</label>
<div class="control">
<input type="text" class="input" name="email" placeholder="Enter E-mail Address" value="{{old('email')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="pincode">Pincode</label>
<div class="control">
<input type="text" class="input" name="pincode" placeholder="Enter Pincode" value="{{old('pincode')}}" required>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button">Submit</button>
</div>
</div>
#if($errors->any())
<div class="notification">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
#endsection
Routes file:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
Route::apiResource('projects','ATGController');
Controller file:
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Mail\ProjectCreated;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class ATGController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('projects.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects')
->withErrors($validator)
->withInput();
}
else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
//
}
}
you have to return validator fails like this, to be able to get $errors in your blade. Check below example for reference and change the code to your parameters
don't forget to import use Illuminate\Support\Facades\Validator;
public function store(Request $request){
$validator = Validator::make($request->all(), [
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects/create')
->withErrors($validator)
->withInput();
}else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}

Laravel: create a button that affect a column in my database

Is it possible to create a button that changes a column value in a table?
I have a column named status in my movimentations table, and I was wondering if it is possible to change the value of this column with a button in my view that can change from active to inactive
this is my view
<div class="container">
<label for="name" class="form-group"><b>Nome</b>: {{ $movs->nameCoop }}</label><br>
<label for="name"><b>Numero</b>: {{ $movs->numCoop }}</label><br>
<label for="name"><b>CPF</b>: {{ $movs->cpfCoop }}</label><br>
<label for="name"><b>Cadastro</b>: {{ $movs->dtCad }}</label><br>
<label for="name"><b>Demissão</b>: {{ $movs->dtDem }}</label><br>
<label for="name"><b>Observações</b>: {{ $movs->description }}</label><br>
<label for="name"><b>Subscritas</b>: {{ $movs->subscritas }}</label><br>
<label for="name"><b>A integralizar</b>: {{ $movs->aintegralizar }}</label><br>
<label for="name"><b>Integralizadas</b>: {{ $movs->integralizadas }}</label><br>
<label for="name"><b>Status</b>: {{ $movs->status }}</label><br>
<td>
<form action="/trans" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="r" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>+</span>
</button>
</span>
</div>
</form>
</td>
<td>
<form action="/mvs" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value={{$cooperado->id}}>
<button type="submit" class="btn btn-primary">
<span>ver mvs</span>
</button>
</span>
</div>
</form>
</td>
this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cooperado;
class CooperadoController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
//$cooperados = Cooperado::all();
$cooperados = Cooperado::orderBy('dtCad', 'desc')->paginate(10);
return view('cooperados.index', compact('cooperados'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('cooperados.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = new Cooperado([
'nameCoop' => $request->get('nameCoop'),
'numCoop'=> $request->get('numCoop'),
'cpfCoop'=> $request->get('cpfCoop'),
'dtCad'=> $request->get('dtCad'),
'description'=> $request->get('description'),
'subscritas'=> $request->get('subscritas'),
'aintegralizar'=> $request->get('subscritas'),
'status'=> $request->get('status')
]);
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado adicionado');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.show', compact('cooperado'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$cooperado = Cooperado::find($id);
return view('cooperados.edit', compact('cooperado'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
$request->validate([
'nameCoop'=>'required',
'numCoop'=> 'required|integer',
'cpfCoop'=> 'required',
'dtCad'=>'required|date',
'subscritas'=>'required'
]);
$cooperado = Cooperado::find($id);
$cooperado->nameCoop = $request->get('nameCoop');
$cooperado->numCoop = $request->get('numCoop');
$cooperado->cpfCoop = $request->get('cpfCoop');
$cooperado->dtCad = $request->get('dtCad');
$cooperado->dtDem = $request->get('dtDem');
$cooperado->description = $request->get('description');
$cooperado->subscritas = $request->get('subscritas');
$cooperado->integralizadas = $request->get('integralizadas');
$cooperado->aintegralizar = $request->get('aintegralizar');
$cooperado->status = $request->get('status');
$cooperado->save();
return redirect('/cooperados')->with('success', 'Cooperado atualizado');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$cooperado = Cooperado::find($id);
$cooperado->delete();
return redirect('/cooperados')->with('success', 'Sucess');
}
}
I've tried to create a function in my route, but didn't work.
I added option button for active and inactive
<form action="/active-deactive" method="POST">
#csrf
<div class="input-group">
<input type="hidden" class="form-control" name="v" value="{{$cooperado->id}}">
<select required class="form-control" id="status" name="status">
<option value="1">Active</option>
<option value="0">De-Active</option>
</select>
</div>
<button type="submit" class="btn btn-primary">
<span>Confirm</span>
</button>
</div>
</form>
controller
public function Confirm(Request $request)
{
$id = $request->input('v');
$status=$request->input('status');
DB::table('tablename')
->where('id',$id)
->update(['status'=>$status]);
}
route
Route::post('/active-deactive','YourController#Confirm')
Of course you can. You can send a request via ajax when clicking on that button:
$.ajax({
type:'POST',
url:'{{ route("NameOfYourRoute") }}',
dataType:'json',
data:{
isActive = $('#theButtonID').val(),
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
if (data.updated) {
alert('Data Updated');
}
}
});
Then in your controller, you can have a function that receives the value of the button (active or inactive) and updated your table in the database:
public function toggleActivity(Request $request)
{
$isActive = $request->get('isActive');
$updated = Model::where(yourCriteria)->update(['isActive' => $isActive]);
return view('YourView', compact('updated'));
}

Laravel 5.1 Upload Files Security

How can I set a security in my upload files that only pdf, doc, jpeg, png and docx can be uploaded?
I'm just trying it but I don't know if it is the right thing to do... just experimenting.. ^_^ But after all it didn't function ^^ ... actually i've got an error.. Try to help me guys for this?
Here's my Controller.php
public function index()
{
$entries = Fileentry::where('user_id',Auth::user()->id)->get();
return view('fileentries.index', compact('entries'));
}
public function store(UploadFiles $request)
{
if($request->file('filename'))
{
$file = $request->file('filename');
$filename = $file->getFilename().'.'.$extension;
$fileExt = $file->getClientOriginalExtension();
$mime = $file->getClientMimeType();
$original_filename = $file->getClientOriginalName();
$description = UploadFiles::input('description');
$user_id = Auth::user()->id;
$file->save();
// Move the file now
$updatedFileName = $filename.'.'.$fileExt;
$file->move('path/to/destination/folder', $updatedFileName);
return redirect('upload');
}
else
{
echo "nothing happen";
}
}
Here's my View.blade.php
#extends('layouts.app')
#section('content')
<form action="{{route('addentry', [])}}" method="post" enctype="multipart/form-data">
<input name="_token" type="hidden" value="{!! csrf_token() !!}" />
<input type="file" name="filefield" required>
<br>
Description <br>
<input type="textarea" name="description">
<br>
<input type="submit">
</form>
<h1> List of your Entries</h1>
<div class="row">
<ul class="thumbnails">
#foreach($entries as $entry)
<div class="col-md-2">
<div class="thumbnail">
<img src="{{route('getentry', $entry->filename ) }}" alt="ALT NAME" class="img-responsive" />
<p>{{ $entry->description }} </p>
{{$entry->original_filename}}
</div>
</div>
#endforeach
</ul>
</div>
nI#endsection
Thank you guys in advance ^^
Make a FormRequest object by issuing the following command:
php artisan make:request YourFormRequest
Now, in your rules method:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'filename' => 'mimes:pdf,doc,jpeg,png,docx',
// and other validation rules...
];
}
Now update your controller:
/**
* Store the form values.
* Don't forget to import the YourFormRequest class
*
* #param \App\Http\Requests\YourFormRequest $request
* #return \Illuminate\Http\Redirect|string
*/
public function store(YourFormRequest $request)
{
if($request->file('filename')) {
$file = $request->file('filename');
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$fileMime = $file->getClientMimeType();
// and rest of the file details
// Move the file now
$updatedFileName = $fileName.'.'.$fileExt;
$file->move('path/to/destination/folder', $updatedFileName);
// or using the Storage class, it is the same
// as what you have written.
}
}
UPDATE 1:
In your YourFormRequest file, replace the authorize method:
/**
* Authorize the request.
*
* #return bool
*/
public function authorize()
{
return true; // replace false with true.
}
Hope this helps you out. Cheers.

Posting content into the database with an image using Laravel

I'm trying to post some stuff into the database using laravel, but It seems not to work...
This is what I get:
The HTML:
{{ Form::open(array('role' => 'form')) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile1">Nieuws afbeelding</label>
<input type="file" name="img">
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
That displays all well....
Exept when I try to 'post' the news, because that is what I try to do, it just refreses the page. The URL to that page is mydomain.com/admin/news/write
My router looks like this:
Route::resource('admin/news/write', 'AdminController#create');
First it was authenticated in a group:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
Route::resource('admin/news/write', 'AdminController#create');
});
This all works, but when I change the Route::resource('admin/news/write', 'AdminController#create'); to Route::post('admin/news/write', 'AdminController#create'); I get an error, that I can't see...
Good, now my controller:
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
if (Input::only('title', 'message'))
{
return Redirect::to('admin/news/write')->with('message', 'Het nieuws werd gemaakt!');
}
}
else
{
return Redirect::to('admin/news/write')->with('message', "Er ging iets mis: ")->withErrors($validator);
}
}
The problem is, I don't know how I can store an image to
/public/pictures/news
And then store the full file name into the database, if someone could help me out... I need a response quick, beacause I have a deadline... :{
Kindest regards
First you need to tell your form using the laravel helper that this is going to be uploading a file...
Form::open(['method'=>'POST', 'role' => 'form', 'files' => true])
In your controller you want to get the file from the input
$imgFile = Input::file('img');
Now to move the file from the temporary location it's been uploaded, to a more permanent location call the following (where $filename is what you want to call the uploaded file)...
$dir = '../storage/app/upload/';
$imgFile->move($dir.$filename);
The path for the root of the app from here is ../ (one up from public) so..
../storage/app/upload/ would be a great location to use for uploaded files.
You can then just write:
$dir.$filename;
back to the database - job done :)
Edit :: -- Your Controller --
Your controller for parsing this is based on resources...
So your route will be:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
}
Your controller itself will have a structure such as (remembering this: http://laravel.com/docs/4.2/controllers#restful-resource-controllers):
class AdminController extends BaseController {
public function index(){...}
public function create(){...}
public function
//The store() method is an action handled by the resource controller
//Here we're using it to handle the post action from the current URL
public function store()
{
$imgFile = Input::file('img');
//processing code here....
}
public function show(){...}
public function edit(){...}
public function update(){...}
public function destroy(){...}
}
I fixed the issue.
My controller:
<?php
class AdminNewsController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('admin.news.create');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admin.news.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
'publish' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/news/create')->withErrors($validator);
}else{
//store
$news = new News;
$news->title = Input::get('title');
$news->message = Input::get('message');
$news->img_url = Input::file('img')->getClientOriginalName();
$news->posted_by = Auth::user()->username;
$news->published_at = time();
$news->published = Input::get('publish');
$news->save();
//save the image
$destinationPath = 'public/pictures/news';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/pictures/news', $file->getClientOriginalName());
}
//redirect
Session::flash('success', 'Nieuws succesvol aangemaakt!');
return Redirect::to('admin/news/create');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My create.blade.php
<div class="portlet-body form">
{{ Form::open(['method'=>'POST', 'role' => 'form', 'files' => true]) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label>Nieuws afbeelding</label>
{{ Form::file('img') }}
</div>
<div class="form-group">
<label>Bericht publiceren?</label>
<div class="radio-list">
<label class="radio-inline">
<span>
{{ Form::radio('publish', '1') }}
</span>
<b style="color:green">Publiceren</b>
</label>
<label class="radio-inline">
<span>
{{ Form::radio('publish', '0', true) }}
</span>
<b style="color:red">Niet publiceren</b>
</label>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
</div>
Then It all work!
Thanks to Matt Barber for the help!

Categories