Can't pass a parameter through a named route - php

I cant figure out what I am missing. I am trying to have a form submit to a controller method through a named route with all of its input and image->id as a parameter. I keep getting a notfoundhttpexception. If I remove /{$id} from the route declaration I get a missing parameter for controller action error. Here is the code:
The route
Route::post('images/toalbum/{$id}', array('as' => 'imgToAlbum', 'uses' => 'ImagesController#addImageToAlbums'));
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', array('as' => 'home', function()
{
return View::make('layouts.default');
}));
Route::get('users/login', 'UsersController#getLogin');
Route::get('users/logout', 'UsersController#getLogout');
Route::post('users/login', 'UsersController#postLogin');
Route::resource('users', 'UsersController');
Route::resource('images', 'ImagesController');
//routes related to images
Route::post('images/toalbum/{$id}', array('as' => 'imgToAlbum', 'uses' => 'ImagesController#addImageToAlbums'));
Route::resource('videos', 'VideosController');
Route::resource('albums', 'AlbumsController');
view that's submitting the form:
#extends('layouts.default')
#section('content')
<?php
$albumarray = array(null => '');
?>
{{ HTML::image($image['s3Url'], $image['altText']) }}
<p>
Title:{{ $image['caption'] }}</br>
Alt-Text: {{ $image['altText'] }}</br>
Description: {{ $image['description'] }}</br>
</p>
{{ Form::open(array('route' => array('imgToAlbum', $image['id']), 'method' => 'post')); }}
#foreach ($albums as $album)
<?php
array_push ($albumarray, array($album['id'] => $album['caption']));
?>
#endforeach
{{ Form::label('Add image to album?') }}
{{ Form::select('album', $albumarray) }}</br>
{{ Form::submit('Add to Album')}}
{{Form::close();}}
<?php
echo $albums;
?>
#stop
#section('footer')
#stop
controller:
<?php
class ImagesController extends BaseController
{
protected $image;
public function __construct(Image $image)
{
$this->image = $image;
}
// add image to album
public function addImageToAlbums($id)
{
dd($album = Input::all());
$image = $this->where('id', '=', $id);
$image->albumId = $album;
$this->image->save();
/*return Redirect::route('image.show', $this->image->id)
->with('message', 'Your image was added to the album');*/
}
}

Maybe this will help someone in the future so instead of deleting here is the answer. removing the $ from images/toalbum/{$id} in the route declaration has resolved the problem.

Related

Laravel - route within view isn't working

I'm learning laravel, working with 3 files, Welcome.blade.php / route.php / tryaction.php and it's a controller.
I made three links that fetched from database table => hug, greet and slap
when I click any link it gives me an error that actions is not defined.
my Welcome.blade.php:
<ul>
#foreach ($actions as $action)
<li>{{$action->name}}</li>
#endforeach
</ul>
my route.php:
<?php
Route::get('/', [
'uses' => 'tryaction#getHome',
]);
//to deal with get requests
Route::get('/{action}/{name?}', [
'uses' => 'tryaction#doget',
'as' => 'benice'
]);
my tryaction.php controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\actionstable;
class tryaction extends Controller
{
public function doget($action, $name = null){
return view('actions.'.$action,['name'=>$name]);
}
public function getHome(){
$actions = actionstable::all();
return view('welcome',['actions'=>$actions]);
}
}
when I replace the href route in welcome.blade.php with # instead of {{ route('benice', ['action' => $action->name]) }} the error stops from showing on
the data are fetched correctly and the data is shown on the page .. the problem in the route and it's that the actions is not defined, here is the error page:

Laravel conflicting routes

My routes.php excerpt:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
});
My PostsController.php excerpt:
/**
* DELETE /admin/posts/{id}
*/
public function destroy($id)
{
// code
}
/**
* DELETE /admin/posts/trash
*/
public function emptyTrash()
{
// code
}
The problem is that Laravel confuses the 'trash' string in a DELETE /admin/posts/trash request as an {id} parameter. As a consequence, the destroy() method is called instead of emptyTrash(). Why and What can I do for this?
Firstly, order matters. Laravel will search the routes for a match in the order you register them. As you figured out, Laravel will take trash as an id and therefore the URI matches the resource route. Since that route is registered before your additional one, it will use the resource route.
The simplest fix is to just change that order:
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
If you don't like that you can try to limit the parameter for your resource route to numbers only. Unfortunately you can't just add a ->where() to the resource route like you could with others.
Instead you have to define a global pattern for the route parameter. The route parameter Route::resource chooses is the resource name (in snake_case).
So this should work for you:
Route::pattern('posts', '[0-9]+');
Somewhere in your view, you should have a button or a link for actually deleting the post. The view should look something like this:
#section('content')
<div class="panel panel-default">
<div class="panel-heading clearfix">
<b>{{ $post->post_name . ' (id:' . $post->post_id . ')' }}</b><br />
<b> {{ link_to_route('overview', 'Go Back To Post List') }} </b>
<div class="pull-right">
// FORM FOR DELETING POST
{{ Form::open(array('route' => array('delete_post', $post->post_id))) }}
{{ link_to_route('edit_post', 'Edit Post', array('id' => $post->post_id), array('class' => 'post_img_button_edit')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete Post', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
<div class="pull-right">
// FORM FOR EMPTYING TRASH
{{ Form::open(array('route' => 'empty_trash')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Empty Trash', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
</div>
/* Additional HTML code within view */
Your controller should be similar to this:
public function destroy($id)
{
$this->post->delete($id);
return \Redirect::route('overview');
}
public function emptyTrash()
{
// code for collecting and emptying Trash
}
And your routes should look similar to this:
Route::delete('admin_posts/admin_posts/{id}/destroy', array('as'=>'delete_post', 'uses'=>'PostsController#destroy'));
Route::delete('posts/trash', array('as'=>'empty_trash', 'uses'=>'PostsController#emptyTrash'));
The name of your route for actually deleting posts be 'delete_post'.
The name of your route for emptying your trash will be empty_trash
Basically you're explicitly defining your routes so that you'll avoid less ambiguity and Laravel will know which routes to take. Hopefully this information will help!

Laravel file upload confusion

So, I am trying to battle the old file upload inside of the Laravel framework but getting a bit lost. I have managed to get the upload to work so the file uploads and saved into an assets folder with a random string name.
This is the form:
<form action="{{ URL::route('account-upload') }}" method="post">
{{ Form::label('file','Upload File') }}
{{ Form::file('file') }}
<br />
{{ Form::submit('Upload') }}
{{ Form::token() }}
</form>
This is the Route:
Route::get('/account/upload', array(
'as' => 'account-upload',
'uses' => 'AccountController#getUpload'
));
Route::post('/account/upload', function(){
if (Input::hasFile('file')){
$dest = 'assets/uploads/';
$name = str_random(6).'_'. Input::file('file')->getClientOriginalName();
Input::file('file')->move($dest,$name);
return Redirect::to('/account/upload')
->withGlobal('Your image has been uploaded');
}
});
this is the method inside AccountController:
public function getUpload(){
return View::make('account.upload');
}
public function postUpload() {
$user = User::find(Auth::id());
$user->image = Input::get('file');
}
I am now trying to enable that to push the string name into the database and also be associated with the user who uploaded it and show as their profile image? Ay pointers would be great!
I have created a row inside of the database named 'file' with the type of text....I am not sure on this point of how to store and view the image.
try this
// the view
{{ Form::open(['route' => 'account-upload', 'files' => true]) }}
{{ Form::label('file','Upload File') }}
{{ Form::file('file') }}
<br />
{{ Form::submit('Upload') }}
{{ Form::close() }}
// route.php
Route::get('/account/upload', 'AccountController#upload');
Route::post('/account/upload', [
'as' => 'account-upload',
'uses' => 'AccountController#store'
]);
// AccountController.php
class AccountController extends BaseController {
public function upload(){
return View::make('account.upload');
}
public function store() {
if (Input::hasFile('file')){
$file = Input::file('file');
$dest = public_path().'/assets/uploads/';
$name = str_random(6).'_'. $file->getClientOriginalName();
$file->move($dest,$name);
$user = User::find(Auth::id());
$user->image = $name;
$user->save();
return Redirect::back()
->withGlobal('Your image has been uploaded');
}
}
}
// and to display the img on the view
<img src="assets/upload/{{Auth::user()->image}}"/>
In order to upload a file, you'll need enctype="multipart/form-data" as an attribute on the <form> element.
If you're using the Form::open() method, you can just pass "files" => true here, but this should allow you to actually use Input::file() correctly.
Next, when actually dealing with the file, you'll need to use something like storage_path() or public_path() and give an absolute path to the file's destination when moving it.
And a tip: you fetch an authed user's model by calling Auth::user().

Laravel - using onclick to submit form from checkbox

I have a simple task list project under Laravel.
When I click a checkbox it does not show a checked condition. (The second item is in the true condition in the database and thus shows checked. I cannot uncheck this item) I have searched for an answer to why on the net but cannot find a solution or reason.
Code:
home.blade.php (in views folder) -
#extends('layouts.main')
#section('content')
<h1>Tasks</h1>
<ul>
#foreach ($items as $item)
<li>
{{ Form::open() }}
<input type="checkbox" onClick="this.form.submit()" {{ $item->done ? 'checked' : '' }}>
<input type="hidden" name="id" value="{{ $item->id }}">
{{ $item->name }}
{{ Form::close() }}
</li>
#endforeach
</ul>
#stop
HomeController.php (inControllers folder) -
<?php
class HomeController extends BaseController {
public function getIndex() {
$items = Auth::user()->items;
return View::make('home', array(
'items' => $items
));
}
public function postIndex() {
$id = Input::get('id');
$user_id = Auth::user()->id;
$item = Item::findOrFail($id);
if($item->owner_id == $userId) {
$item->mark();
}
return Redirect::route('home');
}
}
Item.php (in models folder) -
<?php
class Item extends Eloquent {
public function mark() {
$this->$done = $this->done ? false : true;
$this->save();
}
}
routes.php -
<?php
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#getIndex'))->before('auth');
Route::post('/', array('uses' => 'HomeController#postIndex'))->before('csrf');
Route::get('/login', array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login', array('uses' => 'AuthController#postLogin'))->before('csrf');
in your code, you never update the model's done value. i assume, you want to change it with the post method. so you'd need to take the value from the checkbox name (e.g. Input::get('box-ID'))
you could also create a checkbox using the form class:
// public function checkbox($name, $value = 1, $checked = null, $options = array())
{{ Form::checkbox('name', 'value', true, ['onClick' => 'alert(123)']) }}
reference: Formbuilder -> checkbox
You should modify your form like this. It works me I hope will work for you also.
{{ Form::open(['route' => ['items.update', $items->id], 'class' => 'form-inline', 'method' => 'put']) }}
Thanks

Upon seemingly correct routing getting error Route not defined! - Laravel 4

I'm developing a very basic application using Laravel 4.1 where users can signup and ask question, pretty basic stuffs. I'm now a bit confused about the restful method which would look something like this public $restful = true in laravel 3. Since then laravel has changed a lot and I got stucked with the restful idea. So I decided to leave it and go on developing the skeleton of my application. Everything went well until I created the postCreate method in my homeController to let authorized users submit their question through a form. I believe I routed the method correctly and the index.blade.php view is alright as well. I just can't figure out why I'm getting this following error even though the codes seem to be okay.
Route [ask] not defined. (View: C:\wamp\www\snappy\app\views\questions\index.blade.php)
If you have got what I'm doing wrong here would appreciate if you point it out with a little explanation.
I'm totally new in laravel 4 though had a bit of experience in the previous version.
Here's what I have in the HomeController.php
<?php
class HomeController extends BaseController {
public function __construct() {
$this->beforeFilter('auth', array('only' => array('postCreate')));
}
public function getIndex() {
return View::make('questions.index')
->with('title', 'Snappy Q&A-Home');
}
public function postCreate() {
$validator = Question::validate(Input::all());
if ( $validator->passes() ) {
$user = Question::create( array (
'question' => Input::get('question'),
'user_id' => Auth::user()->id
));
return Redirect::route('home')
->with('message', 'Your question has been posted!');
}
return Redirect::route('home')
->withErrors($validator)
->withInput();
}
}
this is what I have in the routes.php file
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#getindex'));
Route::get('register', array('as'=>'register', 'uses'=>'UserController#getregister'));
Route::get('login', array('as'=>'login', 'uses'=>'UserController#getlogin'));
Route::get('logout', array('as'=>'logout', 'uses'=>'UserController#getlogout'));
Route::post('register', array('before'=>'csrf', 'uses'=>'UserController#postcreate'));
Route::post('login', array('before'=>'csrf', 'uses'=>'UserController#postlogin'));
Route::post('ask', array('before'=>'csrf', 'uses'=>'HomeController#postcreate')); //This is what causing the error
And finally in the views/questions/index.blade.php
#extends('master.master')
#section('content')
<div class="ask">
<h2>Ask your question</h2>
#if( Auth::check() )
#if( $errors->has() )
<p>The following erros has occured: </p>
<ul class="form-errors">
{{ $errors->first('question', '<li>:message</li>') }}
</ul>
#endif
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
{{ Form::token() }}
{{ Form::label('question', 'Question') }}
{{ Form::text('question', Input::old('question')) }}
{{ Form::submit('Ask', array('class'=>'btn btn-success')) }}
{{ Form::close() }}
#endif
</div>
<!-- end ask -->
#stop
Please ask if you need any other instance of codes.
Your 'ask' route is not named. When you pass 'route' => 'foo' to Form::open, that assumes you have a route named 'foo'. add 'as' => 'ask' to your /ask route and it should work.
Alternatively, use URL or Action to resolve the form's target url instead:
Form::open(['url' => 'ask']);
Form::open(['action' => 'HomeController#postCreate']);
you are using name route ask in your form which is not exist. I have created the name route ask for you.
Route::post('ask', array('before'=>'csrf', 'as' => 'ask', 'uses'=>'HomeController#postcreate'));
{{ Form::open( array('route'=>'ask', 'method'=>'post')) }}
^^^^ -> name route `ask`
{{ Form::token() }}

Categories