Laravel redirect to post method - rest

To stay basic I would like to create a bookmark app
I have a simple bookmarklet
javascript:location.href='http://zas.dev/add?url='+encodeURIComponent(location.href)
I created a rest controller
<?php
use zas\Repositories\DbLinkRepository;
class LinksController extends BaseController {
protected $link;
function __construct(DbLinkRepository $link) {
$this->link=$link;
// ...
//$this->beforeFilter('auth.basic', array('except' => array('index', 'show', 'store')));
// ...
}
public function index()
{
//return Redirect::to('home');
}
public function create()
{
}
public function store()
{
return 'hello';
//$this->link->addLink(Input::get('url'));
//return Redirect::to(Input::get('url'));
}
public function show($id)
{
//$url = $this->link->getUrl($id);
//return Redirect::to($url);
}
public function edit($id)
{
}
public function update($id){
}
public function destroy($id){
}
}
in the routes.php, I created a ressource
Route::resource('links','LinksController');
and as I want to redirect /add to the store method I added
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
but it never display the hello message, in place it redirects me to
http://zas.dev/links
I also tried with
return Redirect::route('links.store');
without much success
thanks for your help

Ok I now get what you are trying to do. This will work:
Route::get('add', 'LinksController#store');
Remove:
Route::resource('links','LinksController');
and remove:
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
Sorry it took so long!

The problem is that once you Redirect::, you loose all the Input values, so you should manually give them to your controller when you do the redirect, like so :
Redirect::route('links.store', ["url" => Input::get("url")]);
Finally add an $url parameter to your store method to receive the value we give it in the previous method, like this :
public function store($url) {
$this->link->addLink($url);
return Redirect::to($url);
}

Related

Best practice to redirect Laravel home to another URL?

How I can redirect the Laravel 7 auth home URL to the dashboard.
My route filE route/web.php
use Illuminate\Support\Facades\Route;
Auth::routes();
Route::get('/dashboard', 'HomeController#index')->name('dashboard');
Route::get('/', function () {
return view('/home');
})->middleware('auth');
MyLogin Controller seems like this
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
After spending a few hours on this I found the below solutions
Just Make Changes in app\Providers\RouteServiceProvider.php
public const HOME = '/home';
To
public const DASHBOARD = '/dashboard';
Then make small changes in another files i.e app\Http\Controllers\Auth\LoginController.php
protected $redirectTo = RouteServiceProvider::HOME;
To
protected $redirectTo = RouteServiceProvider::DASHBOARD;
Make a final change in app\Http\Middleware\RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
To
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::PARTNERS);
}
return $next($request);
}
Change your rout to
Route::get('/', function () {
return redirect('/dashboard');
})->middleware('auth');
Not open the CMD and inside the project folder and run the command php artisan optmize:clear and check now by the login.
So simple solution is :
use Illuminate\Support\Facades\Route;
Auth::routes();
Route::get('/dashboard', 'HomeController#index')->name('dashboard');
Route::get('/', 'HomeController#index');

Codeigniter: Can edit form and insert form use the same validation?

This is my function validation for insert article. But when I work with edit article also have form validation and with same condition. So I would like to use only one function validation instead of copy and paste.
function article_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
$this->form_validation->set_rules('content','Article body','required|trim|xss_clean');
if($this->form_validation->run())
{
$this->load->model('article');
$this->article->insert_article();
redirect('article');
}
else
{
$this->load->view('page/insert');
}
}
Try creating an is_valid method in you controller, call it anywhere in your controller, just make your is_valid function private to avoid being routed.
Class Articles {
private function is_valid(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
$this->form_validation->set_rules('content','Article body','required|trim|xss_clean');
return $this->form_validation->run();
}
public function create_article()
{
if($this->is_valid()){
//save in DB
}
}
public function edit_article($id)
{
if($this->is_valid()){
//save in DB
}
}
}

Zend Framework 1.12 plugin for checking "Authorization" header

I'm writing REST api using Zend Framework 1.12. I want to check "Authorization" header in controller plugin.
I put code in the preDispatch action of the plugin
$authorizationHeader = $request->getHeader('Authorization');
if(empty($authorizationHeader)) {
$this->getResponse()->setHttpResponseCode(400);
$this->getResponse()->setBody('Hello');
die(); //It doesn't work
}
The problem is that after it controller's action is still being called. I tried 'die()', 'exit'. My question is how to return response from plugin and do not call controller's action.
Did a similar REST API with Zend several weeks ago with this approach:
Class Vars/Consts:
protected $_hasError = false;
const HEADER_APIKEY = 'Authorization';
My preDispatch:
public function preDispatch()
{
$this->_apiKey = ($this->getRequest()->getHeader(self::HEADER_APIKEY) ? $this->getRequest()->getHeader(self::HEADER_APIKEY) : null);
if (empty($this->_apiKey)) {
return $this->setError(sprintf('Authentication required!'), 401);
}
[...]
}
My custom setError Function:
private function setError($msg, $code) {
$this->getResponse()->setHttpResponseCode($code);
$this->view->error = array('code' => $code, 'message' => $msg);
$this->_hasError = true;
return false;
}
Then simply check if a error has been set inside your functions:
public function yourAction()
{
if(!$this->_hasError) {
//do stuff
}
}
If you're using contextSwitch and JSON, then your array with errors will be automatically returned & displayed, if an error occours:
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$this->_helper->contextSwitch()->initContext('json');
[...]
}
Hope this helps
Since checking headers is typically a low level request operation, you could do the header verification and then throw an exception if not valid in dispatchLoopStartup of the plugin. Then in your error controller, return the appropriate response. This would prevent the action from being dispatched/run and could be applied to any controller/action without modifying any controller code.
Controller plugin:
class AuthHeader extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(\Zend_Controller_Request_Abstract $request)
{
// Validate the header.
$authorizationHeader = $request->getHeader('Authorization');
if ($invalid) {
throw new Zend_Exception($error_message, $error_code);
}
}
}
Error handler:
class ErrorController extends Zend_Controller_Action
{
public function init()
{
// Enable JSON output for API originating errors.
if ($this->isApiRequest($this->getRequest())) {
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('error', 'json')
->setAutoJsonSerialization(true)
->initContext('json');
}
}
public function errorAction()
{
// Handle authorization header errors
// ...
// Handle errors
// ...
}
public function isApiRequest($request)
{
// Determine if request is an API request.
// ...
}
}

Passing the Ajax request data parameter through Zend Framework Controller to model class

I am Using the Zend Framework.
As a design pattern i am using the state design pattern.
Now as you may know, Zend Framework let's you create custom controllers, which can be used to respond to Ajax requests.
In my example i have the following ajax request
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
The function getResponse is called every time a specific button is pressed.
public function ajaxtestAction()
{
$input_in = $this->getRequest()->getParam('button');
$Lok = new Lok();
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
The Code above is my custom response to the ajax request. I want to pass on the name of the pressed button to $Lok = new Lok(); so i can use it in the "Lok" model Class without creating a new instance of The controller in the "Lok" class
Is there anyone who might be able to help me ?
EDIT-----------------------------------
Here's my Controller :
class MotorController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
}
public function ajaxtestAction()
{
$input_in = array($this->getRequest()->getParam('button'));
$phpNativ1 = Zend_Json::encode($input_in);
echo $phpNativ1;
$Lok = new Lok();
echo $input_in;
$this->_helper->viewRenderer->setNoRender();
$text = array($Lok->getMotorState());
$phpNative = Zend_Json::encode($text);
echo $phpNative;
}
}
Here are my Jquery functions :
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
$("input[name=State]").val('Forwards');
});
function getResponse(name){
$.ajax({
dataType: 'json',
data: {button: name},
url: 'motor/ajaxtest',
type: 'post',
success: function(response)
{
}
});
}
$("button[name=on]").click(function() {
var d_response = getResponse('on');
});
});
And this is my Lok.php file :
class Lok
{
private $newMotor;
private $newTimer;
private $newSpeaker;
private $mySession;
private $motorState;
private $input;
public function __construct()
{
//Method instances
$newMotor = new Motor();
$newTimer = new Timer();
$newSpeaker = new Speaker();
$this->motorState = $newMotor->getMotorState();
// Declaring the Session
$mySession = new Zend_Session_Namespace();
$mySession->s_motorState = $this->motorState;
}
public function __get($mySession)
{
return $this->mySession;
}
public function __set($motorState, $mySession)
{
$this->$mySession->s_motorState = $motorState;
}
public function getMotorState()
{
return $this->motorState;
}
public function playSound($soundNumber)
{
echo "Playing sound";
}
public function resetTimer()
{
echo "Resetting timer";
}
public function setInput($input_in)
{
$this->input=$input_in;
}
}
As i've stated previously you should get the button name by calling the requests post data, this is done by $postData = $this->getRequest()->getPost()
Then, to get the output into your Model, inside your model class you would create a property as well as setter and getter method for it.
class Lok {
protected $button;
public function setButton($btn){}
public function getButton(){}
}
And then it becomes as easy as doing something like
$lokModel->setButton($postData['button'])
First of all, thanks for posting your solution.
I tried to implement your solution but unfortunaly it didnt work.
So after a good night sleep, i looked at the problem again. I think the problem is, that
$postData = $this->getRequest()->getPost() or $postData = $this->getRequest()->getParam('button')
is executed in the response itelfe.
<pre>string(2) "sr"
</pre>["Not Moving"]
This is what the JSON response looks like in The Google Chrom debugger. If you'r familliar with this Google Chrome debugger you know what i mean.
Now the button name that i want is in between the &quot tags the only problem is, getting it out of there. and being able to use it before the response is triggerd. I also tried getPost() and getParam('button') in the init() and indexAktion() Methods in the Controller but it still didn't work
public function init()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
public function indexAction()
{
postData = $this->getRequest()->getPost()
$lokModel->setButton($postData['button'])
}
Any other ideas ?

CakePHP and Facebook with Security Component turned on

I want the Security Component turned on.
BUT when you load a CakePHP app inside a Facebook tab, FB posts $_REQUEST['signed_request'] to my form - the problem with this is that the Security Component "reacts" to this "post" and gives me validation errors, black-hole, etc.
How do I go around this?
I could not find anything on the documentation to go around this problem.
What I wanted was to somehow run the Security Component "manually" so that it only "reacts" when I actually submit my form and not when Facebook posts the $_REQUEST['signed_request'] to my form.
UPDATE:
<?php
App::uses('CakeEmail', 'Network/Email');
class PagesController extends AppController {
public $helpers = array('Html','Form');
public $components = array('RequestHandler');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->Security->validatePost = true;
$this->Security->csrfCheck = true;
$this->Security->unlockedFields[] = 'signed_request';
}
public function home() {
$this->loadModel('Memberx');
if($this->request->is('post') && isset($this->request->data['Memberx']['name'])) {
//...save here, etc. ...
}
}
FYI: I get a "black hole" error.
FINAL UPDATE (After #tigrang's answer):
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->set('hasLiked', false);
if(isset($this->request->data['signed_request'])){
$this->set('hasLiked', $this->hasLiked($this->request->data['signed_request']));
}
if(isset($this->request->data['Memberx']['signed_request'])) {
$this->set('hasLiked', $this->hasLiked($this->request->data['Memberx']['signed_request']));
}
/*
To go around Facebook's post $_REQUEST['signed_request'],
we unset the $_REQUEST['signed_request'] and disable the csrfCheck
ONLY after we have set the hasLiked view variable
*/
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
}
Then, I do something like below in my views:
<?php
if($hasLiked) {
?>
You have liked this page!
<?php
}
?>
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->_validateFbRequest();
}
protected function _valdiateFbRequest() {
if (!isset($this->request->data['signed_request'])) {
// not a valid request from fb
// throw exception or handle however you want
return;
}
$signedRequest = $this->request->data['signed_request'];
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
// validate the request
}