Best practice to redirect Laravel home to another URL? - redirect

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');

Related

How to set an attribute to route definition in Slim4 and use it in a middleware

I need to set a custom attribute in the route definition and use it a route middleware. For example, I need to manage the refer page to redirect the user after the login.
This is my routes definition:
return function (App $app) {
$app->get('/', Home::class. ':home')->setName('home');
$app->get('/login', UserAction::class. ':getLogin')->setName('login')->setAttribute('norefer',true);
$app->post('/login', UserAction::class. ':postLogin');
};
The ->setAttribute('norefer',true); is what I'm looking for and seems it doesn't exist.
I need this attribute using ->getAttribute("norefer") in a middleware so I can store the last referable page visited by the user:
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
if (!empty($route) && !$routeContext->getRoute()->getAttribute("norefer")) {
$referName = $routeContext->getRoute()->getName();
$referArgs = $routeContext->getRoute()->getArguments();
$this->session->set("referName", $referName);
$this->session->set("referArgs", $referArgs);
}
return $handler->handle($request);
}
So, in the session I can store the last referable page and use it after the login process to redirect the user to his page.
You could add a NoRefererMiddleware to routes you want to exclude from the redirection logic. NoRefererMiddleware just sets a noreferer attribute to the request object if its called.
<?php
use App\Middleware\NoRefererMiddleware;
use Slim\App;
return function (App $app) {
$app->get('/', Home::class. ':home')->setName('home');
$app->get('/login', UserAction::class. ':getLogin')->setName('login')->add(NoRefererMiddleware::class);
$app->post('/login', UserAction::class. ':postLogin');
};
File: src/Middleware/NoRefererMiddleware.php
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class NoRefererMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withAttribute('noreferer', true);
return $handler->handle($request);
}
}
Usage
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$noReferer = $request->getAttribute('noreferer');
if ($noReferer !== true) {
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
if ($route !== null) {
$referName = $routeContext->getRoute()->getName();
$referArgs = $routeContext->getRoute()->getArguments();
$this->session->set('referName', $referName);
$this->session->set('referArgs', $referArgs);
}
}
return $handler->handle($request);
}

Laravel Backpack Admin CRUD Views returning 404

I had this working on a local dev environment, but now that I'm pushing it live I'm running into an error:
When I try to access my CRUD pages (/admin/images or similar), I get taken to my websites 404 page.
I uploaded the /routes/admin.php file, all my resource files, controllers, models, vendor files, public/vendor files, and probably some others I'm forgetting to mention.
Not sure if theres something in the config files for backpack I need to edit or what. Looking for some direction.
Note: I am able to access the default routes from Backpack (dashboard, login, logout)
RouteServiceProvider.php
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
protected function mapAdminRoutes()
{
Route::middleware(['web', 'admin'])
->prefix('admin') // or use the prefix from CRUD config
->namespace($this->namespace.'\Admin')
->group(base_path('routes/admin.php'));
}
Found this error in the error logs:
exception 'Illuminate\Database\Eloquent\RelationNotFoundException'
with message 'Call to undefined relationship [wheels] on model
[App\Models\WheelFinishes].' in
laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:20
But I have the relationship defined in my WheelFinishes model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
class WheelFinishes extends Model
{
use CrudTrait;
public function wheels()
{
return $this->belongsTo('App\Models\Wheels', 'wheel_id');
}
...
}
Wheels Model
namespace App\Models;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use App\User;
class Wheels extends Model
{
use CrudTrait;
protected $table = "wheels";
protected $primaryKey = 'id';
...
public function tips()
{
return $this->hasMany('App\Models\WheelTips', 'wheel_id');
}
public function finishes()
{
return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
public function factoryFinishes()
{
return $this->hasMany('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->where('factory_finish', '=', '1')->orderBy('order');
}
public function wheelImages()
{
return $this->hasMany('App\Models\WheelImages', 'wheel_id');
}
public function wheelImage()
{
return $this->hasOne('App\Models\WheelFinishes', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
public function profile()
{
return $this->BelongsTo('App\Models\Profile');
}
public function series()
{
return $this->BelongsTo('App\Models\Series');
}
public function vehicles()
{
return $this->hasMany('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order')->take(3);
}
public function vehicle()
{
return $this->hasOne('App\Models\Vehicles', 'wheel_id')->where('status', '=', '1')->orderBy('order');
}
}
routes.php
<?php
// Backpack\CRUD: Define the resources for the entities you want to CRUD.
CRUD::resource('video', 'VideoCrudController');
CRUD::resource('wheels', 'WheelCrudController');
Route::get('finishes/ajax-finishes-options', 'FinishCrudController#wheelsOptions');
CRUD::resource('finishes', 'FinishCrudController');
Route::get('albums/ajax-albums-options', 'AlbumCrudController#albumsOptions');
CRUD::resource('albums', 'AlbumCrudController');
CRUD::resource('heros', 'HeroCrudController');
If you have a separate route file you probably need to register it in RouteServiceProvider:
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
require base_path('routes/admin.php');
});

Laravel redirect to post method

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);
}

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 ?

Language switcher, redirect to current page with symfony

What is the best way to do a language switcher in symfony that redirects to the same page in the chosen language? Jobeet simply redirects on the homepage.
Something like so should do the trick:
<?php
class myActions extends sfActions
{
public function executeLanguageSwitch(sfWebRequest $request)
{
$new_language = $request->getParameter('lang',false);
$this->forward404unless($new_language);
// You should probably insert stuff here check that the new culture passed in is valid
$this->getUser()->setCulture($new_language);
$this->redirect($request->getReferer());
return sfView::HEADER_ONLY;
}
}
This works for me:
<?php
class PageController extends Controller
{
public function changeLocaleAction(Request $request)
{
$locale = $request->get('_locale');
$this->get('session')->set('_locale', $locale);
$referer = $request->headers->get('referer');
return new RedirectResponse($referer);
}
}