L5.3 - Call route from another route - php

I've a simple route into the file web.php:
Route::get('first/{param?}', [
'uses' => 'App\Http\Controllers\MyController#index',
'as' => 'myControllerIndex'
]);
Now, I'd like to create a second route that uses the first route but passing specific params.
I tried something like this:
Route::get('second', function () {
return file_get_contents(route('myControllerIndex', ['param' => 'book1']));
});
but it doesn't work.
Can anyone help me?
Thank you.

You could use a redirect
Route::get('second', function () {
return redirect()->route('myControllerIndex', ['param' => 'book1']);
});
Or you can access the controller directly
Route::get('second', function () {
return app('App\Http\Controllers\MyController')->index('book1');
});

Related

Laravel $id return 'en' instead of id

My route:
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'],
function () {
// GROUP FOR AUTHENTICATION
Route::group([
'middleware' => 'auth:sanctum', 'verified',
], function () {
// GROUP FOR ADMIN
Route::group([
'prefix' => 'admin',
'as' => 'admin.',
], function () {
Route::resource('partner', PartnerFormController::class);
});
});
});
My view that when I click, it shows the details page:
Edit
My controller:
public function show(PartnerForm $partnerForm, $id)
{
$details = DB::table('partner_forms')->where('id', $id)
->first();
return view('admin.partner-details', compact('details'));
}
I tried to call $details->name or $details->in my view details page but it didnt work. The URL is working properly by displaying http://127.0.0.1:8000/en/admin/partner/1 but when i dd() my $id in controller it returns en, which I believe is the en from the URL.
Instead of sending the ID along with the route, send all the variables and enter the information into the new page in the control without the need to connect to the database and using route model binding.
Example :
view A
Foo
route
Route::get('.../{partner}', [Controller::class, 'Bar'])->name('admin.partner.show');
controller
public function Bar(Partner_MODEL $partner){
return view('view_name', compact('partner'));
}
view B : use $partner.
Important note : in (route, controller method, compact meethod) The variable name must be similar

Conditional routing based on Middleware

I need to call different controller for the same url based on a middleware. The url has to be the same, so redirecting in the middleware is not an option. The code below is sample, controllers for dozens for routes are already finished, so checking the session value there is not an option either.
Tried to create two different middleware (has/hasnt the session value), but the latter route group overwrites the previous anyway. Any clue? Maybe a different approach needed?
route.php looks like this:
Route::group(array('namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'auth'), function () {
// set of default routes
Route::get('/', array('as' => 'admin', 'uses' => 'FirstController#index'))->middleware('admin');
Route::get('/profile', array('as' => 'profile', 'uses' => 'FirstController#profile'))->middleware('admin');
Route::group(array('middleware' => 'sessionhassomething'), function () {
// set of the same routes like above but overwritten if middleware validates
Route::get('/', array('as' => 'admin', 'uses' => 'SecondController#index'))->middleware('admin');
Route::get('/profile', array('as' => 'profile', 'uses' => 'SecondController#profile'))->middleware('admin');
});
});
SessionHasSomething middleware:
class sessionHasSomething {
public function handle($request, Closure $next)
{
if(session()->has("something_i_need_to_be_set")) {
return $next($request);
}
// return what if not set, or ...?
}
}
Thanks in advance!
If you are only checking if session()->has('something'), it is possible to use route closures to add a condition within the route which needs to be dynamic.
Below is an example:
Route::get('/', function() {
$controller = session()->has('something')) ? 'SecondController' : 'FirstController';
app('app\Http\Controllers\' . $controller)->index();
});
->index() being the method within the controller class.
We almost have the same issue and here's what I did. (I didn't use middleware).
In my blade.php, I used #if, #else and #endif
<?php
use App\Models\User;
$check = User::all()->count();
?>
#if ($check == '0')
// my html/php codes for admin
#else
// my html/php codes for users
#endif
you can also do that in your controller, use if,else.

NotFoundHttpException - Laravel

i want to make edit-update function..
this is my code :
Admin Controller
public function edit_ist($id_prog)
{
$program_studi = ProgramStudi::find($id_prog);
return view('edit_ist_program_studi',compact('program_studi'));
}
public function update_ist($id_prog)
{
$istUpdate = Request::all();
$program_studi = ProgramStudi::find($id_prog);
$program_studi->update($istUpdate);
return redirect('administrator');
}
Form open in view edit_ist_program_studi
{{ Form::model($program_studi,['method'=>'PATCH','route'=>['update_prodi',$program_studi->id_prog]])}}
Routes:
Route::patch('admin_page/edit_prodi/{id_prog}',
['as' => 'update_prodi', 'uses' => 'AdminController#update_ist']);
But i found error NotFoundHttpException, can you help me to fix this ? thank you
You are missing the GET route to the edit page.
Add something like this:
Route::get('admin_page/edit_prodi/{id_prog}', ['as' => 'edit_prodi', 'uses' => 'AdminController#edit_ist']);

How to pass extra parameters to controller from Laravel route

I'm trying to handle basic validation of my API calls in the Laravel's routes. Here is what I want to achieve:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', 'PropertiesController#getPropertyByProgressStatus', function () {
//pass variable x = 1 to the controller
});
Route::get('waiting', 'PropertiesController#getPropertyByProgressStatus', function () {
//pass variable x = 2 to the controller
});
});
Long story short, depending on the segment of the URI after api/v1/properties/ I want to pass a different parameter to the controller. Is there a way to do that?
I was able to get it to work with the following route.php file:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', [
'uses' => 'PropertiesController#getPropertyByProgressStatus', 'progressStatusId' => 1
]);
Route::get('remodeled', [
'uses' => 'PropertiesController#getPropertyByProgressStatus', 'progressStatusId' => 1
]);
Route::get('pending', [
'uses' => 'PropertiesController#getPropertyByProgressStatus', 'progressStatusId' => 3
]);
Route::get('available', [
'uses' => 'PropertiesController#getPropertyByProgressStatus', 'progressStatusId' => 4
]);
Route::get('unavailable', [
'uses' => 'PropertiesController#getPropertyByProgressStatus', 'progressStatusId' => 5
]);
});
and the following code in the controller:
public function getPropertyByProgressStatus(\Illuminate\Http\Request $request) {
$action = $request->route()->getAction();
print_r($action);
Pretty much the $action variable is going to let me access the extra parameter that I passed from the route.
I think that you can do it directly in the controller and receiving the value as a parameter of your route:
First you need to specify the name of the parameter in the controller.
Route::group(['prefix' => 'api/v1/properties/'], function ()
{
Route::get('{parameter}', PropertiesController#getPropertyByProgressStatus');
In this way, the getPropertyByProgressStatus method is going to receive this value, so in the controller:
class PropertiesController{
....
public function getPropertyByProgressStatus($parameter)
{
if($parameter === 'purchased')
{
//do what you need
}
elseif($parameter === 'waiting')
{
//Do another stuff
}
....
}
I hope it helps to solve your issue.
Take a view for this courses: Learn Laravel or Create a RESTful API with Laravel
Best wishes.
----------- Edited ---------------
You can redirect to the route that you want:
Route::group(['prefix' => 'api/v1/properties/'], function () {
Route::get('purchased', function () {
return redirect('/api/v1/properties/purchased/valueToSend');
});
Route::get('waiting', function () {
return redirect('/api/v1/properties/waiting/valueToSend');
});
Route::get('purchased/{valueToSend}', PropertiesController#getPropertyByProgressStatus);
});
Route::get('waiting/{valueToSend}', PropertiesController#getPropertyByProgressStatus);
});
});
The last two routes response to the redirections and send that value to the controller as a parameter, is the most near that I think to do this directly from the routes.

Laravel redirect to user dashboard when visiting login page if logged in

I have a basic login system setup, but I would like the user to be sent to there dashboard page if they try to access the "login" page or "create account" page.
How do I go about doing this?
I am thinking something in the routes file?:
Route::post('/login', array('uses' => 'UserController#login'));
Route::post('/create-account', array('uses' => 'UserController#createAccount'));
Route::group(array('before' => 'auth'), function () {
Route::get('/dashboard', array('uses' => 'DashboardController#index'));
Route::get('/logout', function () {
Auth::logout();
return Redirect::to('/start');
});
});
Perhaps some kind of group around the first two routes?
A before filter is perfect for this. Since it basically will do the opposite of auth let's call it no_auth:
Route::filter('no_auth', function(){
if(Auth::check()){
return Redirect::to('dashboard');
}
}
And then wrap a group around your two routes to apply the filter:
Route::group(array('before' => 'no_auth'), function(){
Route::post('/login', array('uses' => 'UserController#login'));
Route::post('/create-account', array('uses' => 'UserController#createAccount'));
});
Edit
Actually, as #afarazit points out, there's already a filter like that in app/filters.php called guest. You just have to change the redirect URL to dashboard and you're ready to go.
There's already a filter for what you want, check your filters.php for "guest"
There are many ways to do this. You can use an Event listener like so:
Event::listen('user.login', function (){
if(Auth::check()){
return Redirect::to('dashboard');
}
});
Event::listen('user.create', function (){
if(Auth::check()){
return Redirect::to('dashboard');
}
});
You need a named controller for above like so:
Route::post('/login', array(
'uses' => 'UserController#login',
'as' => 'user.login'
));
Route::post('/create-account', array(
'uses' => 'UserController#createAccount',
'as' => 'user.create'
));
You may use a constructor and include a filter in it. Here is an example; You can modify your code according to the example.
public function __construct(SignInForm $signInForm)
{
$this->signInForm = $signInForm;
$this->beforeFilter('guest', ['except' => 'destroy']);
}
If laravel version is 4.2
open your app/filters.php and add
Route::filter('no_auth', function(){
if(Auth::check()){
return Redirect::to('dashboard');
}
});
add your login and create account pages to your app/routes.php like below:
Route::group(array('before' => 'no_auth'), function(){
Route::post('/login', array('uses' => 'UserController#login'));
Route::post('/create-account', array('uses' => 'UserController#createAccount'));
});
It worked for me.

Categories