Issues with Redirect in Laravel 4.1 - php

I just started trying Laravel 4.1 today, and I've had to use a tutorial for Laravel 4.0, so I've had to troubleshoot certain parts of the code.
There's one part I couldn't troubleshoot, and i need some help with it.
These are the routes involved:
Route::get('authors/{id}/edit', array('as'=>'edit_author', 'uses'=>'AuthorsController#get_edit'));
Route::put('authors/update', array('uses'=>'AuthorsController#put_update'));
and these are the actions in the controller:
public function get_edit($id){
return View::make('authors.edit')->with('title', 'Edit Author')->with('author', Author::find($id));
}
public function put_update(){
$id = Input::get('id');
$author = array(
'name' => Input::get('name'),
'bio' => Input::get('bio'),
);
$validation = Author::validate($author);
if ($validation->fails()){
return Redirect::route('edit_author', $id);
}else{
Author::update($id, $author);
return Redirect::route('view_author', $id);
}
}
Note that in the routes i'm using {id} instead of (:any), because the latter didn't work for me.
On my browser the get_edit function runs ok at first, but then, when i click the submit button and it's supposed to execute put_update, whether it's supposed to redirect me to view_author or back to edit_author, it just gives me a NoFoundHttpException.
Just as additional information, i use the default .htacces which is this one:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Since you are using 4.1 so it should be {id} not (:any) and make sure you are using the right way to generate form, like this:
Form::open(array('action' => array('AuthorsController#put_update', $author->id), 'method' => 'put'))
Also close the form using Form::close(). Since you are not using a RESTful controller so you can use a method name as update instead of put_update and for RESTful method use putUpdate not put_update. So, you may use a route like:
Route::put('authors/update', array('uses'=>'AuthorsController#update'));
Then the method should be:
public function update($id)
{
// ...
if ($validation->fails()){
return Redirect::back()->withInput()->withErrors($validation);
}
else{
Author::update($id, $author);
return Redirect::route('view_author', $id);
}
}
So the form should be like:
Form::open(array('action' => array('AuthorsController#update', $author->id), 'method' => 'put'))
Also change your edit route to this:
Route::get('authors/edit/{id}', array('as'=>'edit_author', 'uses'=>'AuthorsController#edit'));
Make the change in the method as well:
public function edit($id)
{
//...
}

Related

How to get redirected to correct page with silex?

When I go to http://www.example.com/new/index.php/login/
(please note /index.php/ as part of the url.)
After successful login, I get redirects to http://www.example.com/new/welcome/
and that's correct.
but the login screen url should not have /index.php/ as this is Silex restapi.
But when I try login without /index.php/ that would be
http://www.example.com/new/login/
after login this time, I get redirected to new/index.php instead of /welcome/ like last time.
Please help.
my code is below:
Index.php:
$app = Silex\Application;
$app->mount('/login', new Routers\Login());
$app->run();
Routers\Login.php:
namespace Routers;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request ;
class Login implements ControllerProviderInterface
{
public function connect(Application $app)
{
// creates a new controller based on the default route
$controllers = $app['controllers_factory'];
$controllers->get('/', 'Controllers\\Login::index');
$controllers->post('/', 'Controllers\\Login::validate');
return $controllers;
}
}
Controllers\Login.php:
namespace Controllers;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class Login {
public function index(Request $request, Application $app)
{
return $app['twig']->render('login.html');
}
public function validate(Request $request, Application $app)
{
// validation goes here
if ( // invalid ) {
return $app['twig']->render('login.html');
} else {
// valid
header("Location: /welcome");
exit;
}
}
}
htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>
EDIT:
I guess I discovered the issue, the login form is:
<form method="post" action="index.php">
instead of posting data to http://www.example.com/new/login
So how the action url must be? I tried action="/new/login" and it doesn't work. I get no route for POST /login. but this is defined in Routers/Login.php, so why should I get this?
Please advise.
EDIT2:
How can I have named routes in my Routers\Login.php as I am using organized controllers with mount like
$controllers->get('/', 'Controllers\\Login::index');
it seems it doesn't accept bind()? Does organized controllers support named routers?
If you want to let silex find the right route for you,
bind a name to your route declaration:
$controllers->get('/', 'Controllers\\Login::index')->bind('login');
and use it in your twig template
<form method="post" action="{{ path('login') }}">
It should find the url you need.

Lumen GET Requests Return 404 Error

define('ROUTE_BASE', 'lumen/public');
$app->get(ROUTE_BASE . '/', function () use ($app) {
return $app->welcome();
});
$app->get(ROUTE_BASE . '/test', function () use ($app) {
return 'test data : 123 abc !';
});
When I access 'localhost/lumen/public/' I can see the 'lumen welcome page'.
But if I try to access 'localhost/lumen/public/test', I receive the following error.
Error: its not found(404).
Laravel expects the public directory to be the webroot of your domain. As this is not true in your case, you will need to make some alterations to your .htaccess.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /lumen/public
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Also worth noting that instead of using a constant, you can use route groups to achieve the same functionality in your routes.php.
$app->group(['prefix' => 'lumen/public'], function ($app) {
$app->get('/', function () {
//welcome
});
$app->get('test', function () {
return 'test data : 123 abc !';
});
});
your lumen project must be put in webroot of your localhost,domain or virtual host not in subfolder of your webroot without edit your .htaccess.
for access your project in browser : http://lumen.laravel.dev not http://lumen.laravel.dev/public/
I hope this help. sorry for my English :)

Securing Model-Bound Laravel Forms

I have a form using model-binding to enter data into a database. I'm trying to serve it over https but can't figure it out.
Here's the view:
{!! Form::model(new App\MissingHours, ['route' => ['missinghours.store'], 'class' => 'form-horizontal']) !!}
#include('missinghours/_form', ['submit_text' => 'Submit Hours'])
{!! Form::close() !!}
I've tried setting the url to https://appurl/missinghours/store but that clearly didn't work. I also tried model_secure taking after Form::open_secure, and that didn't work. When I serve the page over https and try to submit the form, I get a warning about it being un-secure and the data is not submitted.
Controller:
$input = Input::all();
$save = MissingHours::create( $input );
If you need your whole site to be https - including forms, you can Insert the following codes below RewriteEngine On on your public/.htaccess file:
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
EDIT:
You can create a before middleware like so:
<?php
namespace App\Http\Middleware;
use Closure;
class BeforeMiddleware
{
public function handle($request, Closure $next)
{
if (! $request->secure()) return redirect()->secure($request->getRequestUri());
return $next($request);
}
}
And then use that middleware in your form.
More on Laravel Middlewares here.

Laravel 5 pretty URL not working on wamp

I am new to Laravel, I am working over a small project, using wamp. I was facing problem with pretty URL part, which I figured it out just now.
But now I am getting a weird issue. I have created my application under directory laravel-first-app.
When I am trying to request a page (articles) for example, http://localhost/laravel-first-app/public/index.php/cv, it is showing up the page.
But now if, I request a page for example, http://localhost/laravel-first-app/public/cv, it is saying URL Not Found error.
Below is a brief description what I did.
In my routes.php
Route::get('/', 'WelcomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Route::resource('articles','ArticlesController');
Route::get('articles/delete/{article_id}','ArticlesController#destroy');
Route::get('cv','CvController#index');
Route::get('cv/upload','CvController#upload');
Route::post('cv','CvController#store');
In my CvController
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class CvController extends Controller {
private $pathToCV;
private $fileName;
public function __construct()
{
$this->pathToCV="cv/";
$this->fileName='piyush_cv.doc';
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return response()->download($this->pathToCV.$this->fileName);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function upload()
{
return view('cv.upload');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
dd($request);
if($request->hasFile('cv'))
{
$file = $request->file('cv');
$file->move($this->pathToCV,$this->fileName);
flash()->overlay('File Uploaded','Thanks for uploading the file');
return redirect('cv/upload');
}
flash()->overlay('File was not selected','');
return redirect('cv/upload');
}
}
In .htaccess I have:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Also, for my wamp, I have enabled mod_rewrite module.
Can you please help me out with this? I want to use url http://localhost/laravel-first-app/public/cv instead of http://localhost/laravel-first-app/public/index.php/cv
Please help.
go to the project folder, open terminal and then run php artisan serve it will start localhost:8000 or similar like that then simply go to https://localhost:8000/articles for your required page
I looked carefully to the application structure, I figured out what was the problem.
Now, I resolved the issue and every thing is working fine.
In the Controller, CvController, I had sent a directory CV, and path name was also CV, so it was behaving weirdly.
If you want detailed solution for this, let me know.
Thanks anyways.

Codeigniter .htaccess rewriting for database

I am having difficulties with Codeigniter. I am trying to get data from a MySQL data by passing the record ID as part of the URL
The URL is to be
localhost/site_folder/page/page_title/2
In the above URL, page is the name of the controller and 2 is the primary ID of the record in the database (this could be any number from 1 to 9999).
My controller includes this:
public function index()
{
$this->load->helper('url');
$this->load->model('pages_model');
$id = $this->uri->segment(3,1);
if (empty($id))
{
show_404();
}
$data['page'] = $this->pages_model->get_page($id);
$this->load->view('page',$data);
}
My .htaccess contains this
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
When I enter localhost/site_folder/page/page_title/2 into the address bar, it throws a 404.
Yet, when I enter localhost/site_folder/page it shows the default database entry as shown in the second value of segment(3,1) above.
So, how should I change the .htaccess file for a workable rewrite?
I have tried the following, but none worked for me:
RewriteRule .* page/$0 [PT,L]
RewriteRule .* page/(*.)/$0 [PT,L]
RewriteRule .* page/(?*.)/$ [PT,L]
You can try using the _remap function as described in the CI documentation https://ellislab.com/codeigniter/user-guide/general/controllers.html
The _remap function if exists in a controller is the a function that is called before any class method, and in this function you can check params sent to the function and according to this call any method of the controller.
For your example as i assume that page_title is dynamic you can either set a regular expression to check it or as i n the following example check if the method does not exists then treat it as a page title (this means that you must be sure there can not be a page title and a method name in this controller with the same name)
public function _remap($method, $params = array())
{
if (!method_exists($this, $method))
{
// assume this is a page_title and run the index method
$this->index($method, $params);
}
else {
// means that method exists then run that method
$this->$method( $params);
}
}
Also remember that means that you should take into consideration in the index method usage of 404 header when someone just type random string that the controller will treat as a page_title.

Categories