Laravel3 how to send variable into controller from view - php

I'm learning laravel 3 at the moment, and I have a technical question. I have a list of authors and I'm trying to make some links to set a filter to order those authors.
I tried setting a default parameters to order by Name, it works, but I can't pass any other filters.
This is my route :
Route::get('authors', array('as'=>'authors', 'uses'=>'authors#index'));
And this is my controller function :
public function get_index($filter="name"){
return View::make('authors.index')
->with('title', 'Authors list')
->with('authors', Author::order_by($filter)->get());
}
And this is the links in my view trying to send the filter I want
{{ HTML::link_to_route('authors', 'Id', array('id')) }}
{{ HTML::link_to_route('authors', 'Name', array('name')) }}
The parameters I try to send (id and name) from the view never reach the controller so it always use default parameter.
Thank you !

You're not setting any route parameters, you must do something like:
Route::get('authors/(:any?)', array('as'=>'authors', 'uses'=>'authors#index'));
Take a look at the docs: http://three.laravel.com/docs/routing#wildcards

Related

Load list of active users from database with symfony without using a controller

I'm making a presonification menu on my navbar so that i can access from any page i don't want to use the getRepository inside a controller and pass to the frontend.
Is there a way on symfony 4 that I can get all the users from my database and call it to front? like the app.session.user (to get info on the logged user) for example?
Thanks!
As Cerad mentioned, you can embed a Controller in your templates : https://symfony.com/doc/current/templates.html#embedding-controllers
Instead of doing {% include 'base/navbar.html.twig' %} you will do
In your template :
{{ render(controller('App\\Controller\\BaseController::renderNavbar')) }}
In BaseController
public function renderNavbar(UserRepository $userRepository) {
return $this->render('base/navbar.html.twig', [
'activeUsers' => $userRepository->findActiveUsers(),
]);
}
It's not a route, it's simply a function that renders html, so you don't need to add annotations.

PHP How to create urls properly?

I have never understood how to create proper URLs. Every time I end up with trying to figure out if I should do ?var=value or &var=value and then if ?var=value already exists then I end up with ?var=value&var=value.
P.S. I am working with Laravel. (So maybe there is a built-in function?)
For example:
I have pagination and my URL could look like this
www.example.com OR
www.example.com?name=John
Then my pagination link is href="?page=2" and I end up with
www.example.com?name=John?page=2
Then I want to navigate to the next page with href="?page=3" and I end up with this. Because it keeps on adding.
www.example.com?name=John?page=2?page=3
What a mess.... is there a function for PHP or Laravel that would create proper URLS? (knowing when to use ? or & and not add existing values all the time but replace them if they exist already.
If you're using Laravel I think you should use some helper functions:
route('user.profile', ['id' => 1]);
It will create url by route name and parameters, It will look like:
http://sitename/user/profile?id=1
And you can find some useful helper functions here
There should be one and only ? in URL's which separates URI and parameters, rest of the key-value pairs are separated by &, and if you need to pass & or ? as a parameter, then you need to encode them.
you could pass an array to http_build_query and it will build the url for you
and in laravel there are url helper functions you can use them with ease.
Laravel come with a route helper which allow you to generage url quickly by passing the name with which you register your route.
Route::get('/', 'HomeController#index')->name('home.route')
Here you can see I pass home.route to the name method which is the name which I use for this route. And when I want to generate the URL for that route in my view I will juste do
{{ route('home.route') }}
If ny route take some parameters like this
Route::get('/person/{id}', 'HomeController#index')->name('home.route')
In view I will generate the url like this
{{ route('home.route', ['id' =>$id]) }}
Because you want juste to make pagination, Laravel comme with a buil in pagination. When you want to paginate something in your views, you must just call the paginate function on your model and laravel will handle all the route for that. For example I you have a Person Model you can do that like this in your controller
$persons = Person::paginate(25)
And in your views to generate pagination for that you will have to do
{{ $persons->links() }}
And that's all

Framework Laravel: view records using specific condition

I have never learnt this framework. As a beginner, I have to modify/add a link in the existing software which is made by some professional team. Could you people can help me out of this situation?
There is a function that shows the records on the main page public function index(). It has return View::make('Titles.Index')->withType('movie');. But I have to add a parameter that shows only english movies having field name language can have 'en' as its value. Would you suggest what needs to be done that it will show up using this condition? I have tried return View::make('Titles.Index')->with('language','en'); but it shows error on the main page.
Basically, index is a controller method that handles the view for your specific route.
Inside the controller method, you can filter the movies and pass a collection to the view. Considering that you have a model called Movie with namespace App\Movie so you can do something like:
public function index() {
// Returns a collection with movies where language field
// is equal 'en'.
$moviesEn = App\Movie::where('language', 'en')->get();
return View::make('Titles.Index')->with('moviesEn', $moviesEn);
}
This code injects the moviesEn variable inside your Titles.Index view. So there you can use it:
#foreach ($moviesEn as $movie)
{{ $movie->title }}
#endforeach

set variables to twig when redirect link?

i want to set a variable to twig when redirect link like when use the render methods :
return $this->render('socialBundle::index.html.twig',array(
'id' => $id
));
it will set the Id variable to twig : {{ id }}
return $this->redirect($this->generateUrl("tuto_animaux_voir", array(
'id' => $id
)));
it will set the Id variable to the link : xxxxx.com/Id , i want that it render this variable to twig when redirect ...
sorry for this bad concept and language because i'm not england , and this is my first question in stackoverflow ,
wait for a reponse , thanks
I don't quite understand what you want to do, if you want to put a link in a twig template or just redirect from a controller according a condition. if you can give more details of what you want to do I think I can help you.
UPDATE (solution)
You could use "Forwarding to Another Controller" instead of using "Redirect" and from there to send the variables to the twig template
Based on your last comment, I came to the following conclusion.
Assume that you have index action, with route tuto_animaux_voir. And route has one parameter id. It takes id as parameter and fetches alert from the database(we have alerts on the database). Also we have entity Alert with fields id(default), title.
...
public function indexAction($id){
$alert = $this->getDoctrine()->getEntityManager("AppBundle:Alert")->find($id);
return $this->render("AppBundle:Post:index.html.twig", array(
'alert' => $alert
));
}
In your template index.html.twig you can show your alert.
...
{{ alert.title }}
...
If you want to redirect to the index action in the twig.
<a href="{{ path("tuto_animaux_voir", { 'id': alert_id })}}">Alert Title<a>
Also if you want render this action as partial.
{{ render(controller('AppBundle:Alert:index',{'id': alert_id})) }}
I think my answer would be helpful for you.
In you case 'tuto_animaux_voir' is a route associated to controller action. Given id will be available as action parameter, so you can pass it like this:
public function fooAction($id)
{
return $this->render(
'socialBundle::foo.html.twig',
['id' => $id]
)
}
You can also fetch data from database and pass them to the view.
If that's not what to you want to achieve, tell us why you want to use redirect, and what these two actions should do.
Edit:
If I understood your comment correctly, you want to implement flash messages, which are already available in symfony.
Example in docs is simple and self-explanatory.

Laravel updating database route

I'm trying to update a column in my database with a total of votes on a project. I'm having a 404 problem but I don't see the problem in my route. (PS: Laravel 3)
This is my Vote button on every project :
{{ Form::open('project/addvote', 'VOTE') }}
{{ Form::hidden('id', $project->id) }}
{{ Form::submit('Vote') }}
{{ Form::close() }}
So when you click on the vote button it use this route :
Route::put('project/addvote', array('uses'=>'projects#addvote'));
And this is my action in the projects controller (no updating yet, just trying to redirect) :
public function put_addvote(){
return Redirect::to_route('project', $id)
->with('message', 'Vote successful');
}
Redirecting to this route :
Route::get('project/(:num)', array('as'=>'project', 'uses'=>'projects#project'));
And this is getting me the 404 error
Thanks to every response and the great help here!
Actually, Redirect::to_route expects a name of a route to redirect to it and a named route has to be declare with a name, like,
Route::put('project/addvote', array('as' => 'project', 'uses'=>'projects#addvote'));
So, you can use it;s name to redirect to it like
return Redirect::to_route('project');
Here, project has been used as it's name using 'as' => 'project'. In, your example, you didn't gave any name to the route, here
Route::put('project/addvote', array('uses'=>'projects#addvote'));
The, as => 'route_name' is missing.
For second question, you can do it as
$id = Input::get('id');
Project::find($id);
Project->votenumber = 5;
Project->->save();
Inserting & Updating Models.
Update :
It was a bit confusing but after a conversation through the commenting system the answer for routing is give below :
You (OP) mentioned that you have a route declared as
Route::get('projets', array('as'=>'projets', 'uses'=>'projets#index'));
To this route you are trying to redirect using this
return Redirect::to_route('project', $id);
So, you are passing a parameter and it's not in your route declaration and this is the problem, so to overcome this change your route declaration to this
Route::get('projets/(:num)', array('as'=>'projets', 'uses'=>'projets#index'));
Or
Route::get('projets/(:any)', array('as'=>'projets', 'uses'=>'projets#index'));
Or, you can make the param optional using a ?, for example :
Route::get('projets/(:any?)', array('as'=>'projets', 'uses'=>'projets#index'));
Check wildcard Routes.
Update :
You should have postd the original code with the question, anyways, Change this
return Redirect::to_route('project', $id);
to
return Redirect::to_route('project', array($id));

Categories