How to dynamically handle Laravel routes using variable in slug - laravel

I want to have a route entry that dynamically handles requests based on the slug in the URL. I tried the code below, but the closure seems to be getting in the way. I replaced the closure with controller actions, too, and tried other options without success. The best I came up with thus far is below:
$bladeFiles = [
"about-us",
"join",
"contact",
];
foreach ($bladeFiles as $thisView) {
Route::get($thisView, function () {
global $thisView;
if (View::exists($thisView)) {
return view($thisView);
} else {
return redirect()->route('homepage');
}
})->name($thisView);
}
The issue with the above snippet is that global $thisView is always null inside the closure.
Thoughts?

Try passing the $thisView through with the use:
$bladeFiles = [
"about-us",
"join",
"contact",
];
foreach ($bladeFiles as $thisView) {
Route::get($thisView, function () use ($thisView) { // <-- here
if (View::exists($thisView)) {
return view($thisView);
} else {
return redirect()->route('homepage');
}
})->name($thisView);
}

Hello i'm doing something very similar to what you want
Route::get('pages/{pageName}',function($pageName){
if(view()->exists('pages.'.$pageName)){
return view('pages.'.$pageName);
} else {
return redirect('/');
}
});
so what i'm doing is i'm having a folder with the name pages
i write the views into that folder with the slug names like contact-us.blade.php
when i go to the route "pages/contact-us" it searches for that view in the folder
if it exists it returns the view else just redirect to the home page
the only difference in my code that you will have to call the routes like that
{{url('pages/"$pageName"')}} instead of {{rout($pageName)}}
i hope my code helps

Related

Route not defined when passing parameter to a route

I have a named route with a parameter which looks like this...
Route::get('/profile/{user_id}', [ProfileController::class, 'profile'])->name('profile');
Now in one of my controller,
I have a function that calls this route like this
public function _myFunction($some_data) {
return redirect()->route('profile', [$some_data->user_id]);
}
and in my ProfileController's profile() function, I have this.
public function profile() {
return view('modules.profile.profile');
}
I've followed the documentation and some guides I found in SO, but I got the same error,
"Route [profile] not defined."
can somebody enlighten me on where I went wrong?
Here's what my routes/web.php looks like...
Route::middleware(['auth:web'])->group(function ($router) {
Route::get('/profile/{user_id}', [ProfileController::class, 'profile'])->name('profile');
});
When calling the route, you should pass the name of the attribute along with the value (as key vaue pairs). In this case, your route is expecting user_id so your route generation should look like this:
return redirect()->route('profile', ['user_id' => $some_data->user_id]);
Read more on Generating URLs To Named Routes in Laravel.
I solved the issue, and its really my bad for not providing a more specific case information and made you guys confused.
I was using socialite and called _myFunction() inside the third party's callback..
After all, the problem was the socialite's google callback, instead of placing the return redirect()->route('profile', [$user->id]) inside _myFunction(), what I did was transfer it to the callback function.
So it looked like this now...
private $to_pass_user_id;
public function handleGoogleCallback()
{
try {
$user = Socialite::driver('google')->user();
$this->_myFunction($user);
return redirect()->route('profile', [$this->to_pass_user_id]);
} catch (Exception $e) {
dd($e->getMessage());
}
}
public function _myFunction($some_data) {
... my logic here
$this->to_pass_user_id = $some_value_from_the_logic
}

conditional nested routes in laravel

I want to check segment of particular URL on route and based on value of segment decide it to handle to another route.Somewhat like below:
Route::get('{module}/{seg}', function(){
if (is_numeric((Request::segment(3)) {
return Route::get('{module}/{seg}',Request::segment(2) . 'Controller#index');
}else{
return Route::get('{module}/{seg}',Request::segment(2).'Controller#index' . Request::segment(3));
}
});
I don't think above code works but can anyone suggest a working code for implementing above logic in laravel?
I'd suggest adding it as an optional parameter, and handle differences in the controller. Given your code, it might look like this, for instance:
// route
Route::get('{module}/{seg}/{param?}', 'Controller#index');
// controller
public function index($module, $seg, $param = null)
{
// for dynamic index methods
if (is_numeric($param)) {
$method = 'index' . $param;
return $this->{$method}();
}
// for non-numeric third-segment params, continue here as usual
}

Laravel Custom User Roles & Permissions based on routes

I've created a custom roles manager for Laravel (4.2) based on the named routes e.g.:
users.index, customers.create, vendors.update, orders.store, users.edit, customers.update, etc.
Basically anything registered as a Route::resource(...); within the routes.php file (with a few custom named routes)
I'm checking the permissions with this method:
namespace Acme\Users;
...
class User extends \Eloquent implements UserInterface, RemindableInterface {
...
public function hasPermissions($route)
{
$actions = ['users.index', 'users.create', 'users.edit', 'users.delete']; // fake data
if ( ! in_array($route, $actions))
{
return false;
}
return true;
}
}
Then, within the app/filters.php, I'm checking the current route against the User.
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
// check if the current authenticated User has permissions to access this route
if ( ! Auth::user()->hasPermissions(Route::current()->getName()))
{
return Redirect::route('dashboard.index');
}
});
Everything is working with any route using the GET method, but when it comes to PUT, PATCH, POST DELETE the Route::current()->getName() doesn't return anything.
Is there a better approach? I want everything to happen automatically, and I have a solution to this issue, but it's very involved. Is there a way to get the route name during a PUT, PATCH, POST or DELETE request?
Thank you.
Try to put your verification code inside after filter.
App::after(function($request, $response)
{
if ( ! Auth::user()->hasPermissions(Route::current()->getName()))
{
return Redirect::route('dashboard.index');
}
});

codeigniter, how to use url segment to direct to the view

I am a newbee to codeigniter
I have a website with three pages. (Home about Contact)
I want to put an anchor to each of them and
catch last segment using $this->uri->segment() in controller's index function.
Then using a switch I want to direct to exact pages.
This is one of my anchor:
<h3 id="anchor_storefront"><?php echo anchor('jstorecontroll/home', 'Home'); ?></h3>
And this is my code in index at controller:
switch( $this->uri->segment(2) )
{
case "":
case "home":
$this->load->view('public/home');
break;
}
Can an expert guide me?
Thanks
How about just having a function for each page? This follows CodeIgniter's usual URI pattern example.com/class/function/id/ - something like this:
class Jstorecontroller extends CI_Controller
{
function index()
{
//Do what you want... load the home page?
}
//Load the 'home' page
function home()
{
$this->load->view('public/home');
}
//Load the 'about' page
function about()
{
$this->load->view('public/about');
}
//Load the 'contact' page
function contact()
{
$this->load->view('public/contact');
}
}
Routing can be used to map URLs: To map jstorecontroll as the first segment and anything as the second segment to the index function in your jstorecontroll controller, you could use this route (in application/config/routes.php):
$route['jstorecontroll/(:any)'] = "jstorecontroll/index/$1";
You may want to use regex to restrict what is mapped though, for example:
$route['jstorecontroll/([a-z]+)'] = "jstorecontroll/index/$1";
You could then have a function in your controller that would filter through and load the corresponding page. However, be wary of the user input - don't trust them! Make sure you sanitise the input.
class Jstorecontroll extends CI_Controller
{
function index($page = FALSE) //Default value if a page isn't specified in the URL.
{
if($page === FALSE)
{
//Do what you want if a page isn't specified. (Load the home page?)
}
else
{
switch($page)
{
case "home":
$this->load->view('public/home');
break;
case "about":
$this->load->view('public/about');
break;
case "contact":
$this->load->view('public/contact');
break;
}
}
}
}
The use of the above route may produce undesired results if you have other function in this controller that you want to be called from a URI, they won't be called but instead mapped as a parameter to the index function. Unless you look at changing (or adding) the routes, or you could look into remapping functions. Personally, I'd just use a function for each page!

Redirect to show_404 in Codeigniter from a partial view

I am using the HMVC pattern in CodeIgniter. I have a controller that loads 2 modules via modules::run() function and a parameter is passed to each module.
If either module cannot match the passed paramter I want to call show_404(). It works, but it loads the full HTML of the error page within my existing template so the HTML breaks and looks terrible. I think I want it to redirect to the error page so it doesn't run the 2nd module. Is there some way to do that and not change the URL?
Is it possible to just redirect to show_404() from the module without changing the URL?
Here is an over simplified example of what's going on:
www.example.com/users/profile/usernamehere
The url calls this function in the users controller:
function profile($username)
{
echo modules::run('user/details', $username);
echo modules::run('user/friends', $username);
}
Which run these modules, which find out if user exists or not:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
show_404(); // This seems to display within the template when what I want is for it to redirect
else
$this->load->view('details', $details);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
show_404(); // Redundant, I know, just added for this example
else
$this->load->view('friends', $friends);
}
I imagine there is just a better way to go at it, but I am not seeing it. Any ideas?
You could throw an exception if there was an error in a submodule and catch this in your controller where you would do show_404() then.
Controller:
function profile($username)
{
try{
$out = modules::run('user/details', $username);
$out .= modules::run('user/friends', $username);
echo $out;
}
catch(Exception $e){
show_404();
}
}
Submodule:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
throw new Exception();
else
// Added third parameter as true to be able to return the data, instead of outputting it directly.
return $this->load->view('details', $details,true);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
throw new Exception();
else
return $this->load->view('friends', $friends,true);
}
You can use this function to redirect 404 not found page.
if ( ! file_exists('application/search/'.$page.'.php')) {
show_404(); // redirect to 404 page
}
its very simple , i solved the problem
please controler name's first letter must be capital e.g
A controller with
pages should be Pages
and also save cotroler file with same name Pages.php not pages.php
also same for model class
enjoy

Resources