Route Passing a value - php

newbie in laravel.
In laravel sample routing
Route::get('books/{genre}', 'controller#method');
The link would be something like this
link.com/books/crime or link.com/books/programming
how do i do it if I want to get both genre?
if this possible is to achieve
link.com/books?genre=crime,programming
how do i write that in routes? and also how do i get the value in controller?
I have tried something like this. But I don't have any idea how to achieve it.
Route::get('books?{genre?}', 'controller#method');
Controller part
function method($fields = null) {
return jsonData;
}
Found a way but its kinda awful...
route
Route::get('books', 'controller#method');
url
link.com/books?genre=crime,programming,love,religion
method
function method() {
$array = explode(',',$_GET['fields');
//.....
return jsonData;
}

there are few ways you can achieve that.
if want to achieve,
http://link.com/books/crime/programming
or
http://link.com/books/crime
you can use the following routes:
Route::get('books/{genre}/{genreOptional?}', function($genre, $genreOptional = null)
{
dd($genre, $genreOptional);
});
or
Route::get('books/{genre}/{genreOptional?}', 'controller#method' );
Your controller:
public function method($genre, $genreOptional = NULL)
{
//
}

Related

Is there a way to use Laravel's getRoutes() to only return routes that aren't redirects?

I've been trying to use Laravel's Route::getRoutes() method to generate a dynamic sitemap. The problem is that that method returns routes that are in reality redirects:
Example web.php:
Route::get('not-redirected', function() {
return view('not-redirected');
}
Route::get('redirected', function() {
return redirect('was-redirected');
}
Route::getRoutes() returns ['not-redirected', 'was-redirected']. Is there a way to dynamically filter out redirected routes from this output?
My desired output for the above web.php would be ['not-redirected'].
EDIT: I've noticed that php artisan route:list does not return redirects. However, I can't figure out why just by looking through the source code... It looks like it calls that same function, Route::getRoutes().
It seems there is no way to determine the return for a given route.
The solution I came up with is to add a group all the routes that are 'special', this way you can easily add custom attributes to a route's action.
Route::group(['return_type' => 'redirect'], function () {
Route::get('not-redirected', function () {
return view('not-redirected');
});
Route::get('redirected', function () {
return redirect('was-redirected');
});
});
Then you could loop over the routes like this:
$routes = Route::getRoutes()->get();
foreach ($routes as $route) {
if ($route->getAction('return_type') === 'redirect') {
// Or whatever you want to do in this case
continue;
}
}

Url in Route Laravel

i want to use url like: http:localhost:8000/api/students/?key=value.
My API is set up as follows:
Route::get('students/{key},'Controller#method')
but my url is: http:localhost:8000/api/students/value
Could anyone help me please?
If you want to pass the key as a $_GET param you want to change your route to just be:
Route::get('students/,'Controller#method')
That way you can use http:localhost:8000/api/students/ and pass any parameters you want
Change Your Route :
Route::get('students,'Controller#method')
in Your Controller use
$request->input('key') or $request->query('key')
public function method(Request $request){
$value = $request->query('key');
$value2 =$request->input('key');
echo $value;
echo $value2;
}
Route::prefix('api')->group(function () {
Route::get('students/{key}','Controller#method');
// here come api-prefixed routes
});
https://laravel.com/docs/5.6/routing#route-group-prefixes

How can i define global variables in slim framework

How can i define a global variable such that my current_user method can work were ever i want it to, all i simple need to do is check if there is a current user my example code is below
if (isset($_SESSION['company_id'])) {
$current_user = Companies::find($_SESSION['company_id']);
}
else
{
$current_company = null;
}
how can i use the current user method where ever i want without passing it to my app->render() method just like in my header.html
{% if current_user %}
hi {{current_user.name}}
{% endif %}
You can inject a value into the app object:
$app->foo = 'bar';
More on Slim’s documentation.
Injection is not working in the callback function.
To have access to the variable in a callback function you can use "use() " function :
$mydata = array ( ... );
$app->get('/api', function(Request $request, Response $response) use($mydata) {
echo json_encode($mydata);
});
Inject the object it like this:
$app->companies = new Companies();
You can also inject it as a singleton if you want to make sure its the same one each time:
$app->container->singleton('companies', function (){
return new Companies();
});
The call it like this:
$app->companies->find($_SESSION['company_id']);
UPDATE DOC LINK:
Slim Dependency Injection
The accepted answer does not work for Slim 3 (as the hooks have been removed).
If you are trying to define a variable for all views and you are using the PhpRenderer, you can follow their example:
// via the constructor
$templateVariables = [
"title" => "Title"
];
$phpView = new PhpRenderer("./path/to/templates", $templateVariables);
// or setter
$phpView->setAttributes($templateVariables);
// or individually
$phpView->addAttribute($key, $value);
i was finally able to get it to work with this
$app->hook('slim.before.dispatch', function() use ($app) {
$current_company = null;
if (isset($_SESSION['company_id'])) {
$current_company = Company::find($_SESSION['company_id']);
}
$app->view()->setData('current_company', $current_company);
});
With twig/view
creating a middleware
<?php
namespace ETA\Middleware;
class GlobalVariableMiddleware extends Middleware {
public function __invoke($request, $response, $next) {
$current_path = $request->getUri()->getPath();
$this->container->view->getEnvironment()->addGlobal('current_path', $current_path);
return $next($request, $response);
}
}

Laravel 3 - why does sending parameters to Redirect::to_route not work

I am wondering why the parameters aren't recognized in this way:
return Redirect::to_route('new_snippet', array(Input::get('snippet'), $validation_errors[0]));
or this way:
return Redirect::to_action('snippet#new', array(Input::get('snippet'), $validation_errors[0]));
while they are in this manner
return $this->get_new(Input::get('snippet'), $validation_errors[0]);
by calling this function in the controller:
public function get_new($default_snippet = '', $error = null)
{
#code
}
I hope that anyone can briefly explain this. I am asking because this only works if all of it happens in the same controller.
Thanks

Codeigniter user profile URL

I have a controller called user which just loads the user profile page for now
class user extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function index($username = null){
//load index page
$this->load->view('profile/index');
}
}
i have also routed it so i can load it from user/$username in routes
//user profiles pretty url
$route['user/(:any)'] = "user/index/$1";
the thing is i would like to change it and allow directly the users to go to their profiles without typing user/$username and instead $usernamd like mysite.com/$username...
I tried it but it messes up everything.how can i achieve this?
Thanks.
I guess the only way to achieve something like this is to add all other controllers to your routes file.
You could try something like this
$route['controller'] = "controller";
$route['controller/(:any)'] = "controller/$1";
$route['(:any)'] = "user/$1";
Combined with the _remap function as stated here. In your users controller.
Have you heard of the _remap function?
If you replace the index() function with this:
public function _remap($username = null) {
$this->load->view('profile/index');
}
It will probably work. You don't have to use the routes.php.
I used something like this for my users ; this "p" function in my users controller, mysite.com/users/p/$user_id , routes are good but I solved it like this, you could also do it do index function if you don't want something like "p"
function p()
{
$total_slashes = count ( $this->uri->segment_array () );
$last = end ( $this->uri->segments );
if ($total_slashes == 3) {
$data ['userdetails'] = $this->users_model->userDetails ( $last );
// $last is our user_id
$this->load->view('profile/index');
}
}

Categories