I have created the following method in an News model in a Laravel project:
public function path() {
return route('news.show', $this);
}
Now, this works just fine and returns the following url structure: www.mydomain.com/news/{id}
However, I would like to tweak it a bit. I want my url structure to be like this: www.mydomain.com/news/{id}/{slug}
So, what I want to know is how do I have to modify the path function in order to return this url structure - i.e., the one with both the id and the slug?
Here is one solution that I tried:
// web.php
Route::get('news/{article}/{slug}', 'NewsController#show')->name('news.show');
// News.php
class News extends Model
{
public function path() {
return route('news.show', $this);
}
}
I then fire up tinker and run that path function and get the following error:
Illuminate/Routing/Exceptions/UrlGenerationException with message 'Missing required parameters for [Route: news.show] [URI: news/{article}/{slug}].'
I have tried other variations -- but nothing seems to work.
Any idea how to tweak this so that it does work?
Thanks.
// web.php
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
You need to pass article id and slug
// News.php
class News extends Model
{
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
}
Related
After setting up a controller and a view to show a specific entry from my database, I wanted to use laravels function of Route Model Binding to fetch the data fromn the database and pass it to the view. However I am getting following error:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with
message "Argument 2 passed to
Symfony\Component\HttpFoundation\RedirectResponse::__construct() must
be of the type integer, array given, called in
C:\xampp\htdocs\laravel\Cyberchess\vendor\laravel\framework\src\Illuminate\Routing\Redirector.php
on line 203"
I've tried to add this line to TrustProxy:
protected $headers = Request::HEADER_X_FORWARDED_ALL;
as the internet recommended, but when I opened the file, I realised it was already in the code.
My create/store works properly, which is why I assume it has something to do with Route Model Binding. I'm currently using a getRouteKeyName() to change the Key to 'AccID' so it should work.
//my controller
public function show(account $account){
//$account = account::where(['AccID' => $account])->get();
//dd($account);
return redirect('user.show', compact('account'));
}
//my model
class account extends Model
{
public function getRouteKeyName() {
return 'AccID';
}
public $timestamps = false;
}
//my view
<h1 class="title">Your Profile</h1>
<p>{{ $account->Nick }}</p>
I expected it to work just fine(duh), but got said error. When I dd(); the data, it has the information I want inside #attributes and in #original.
If if comment the dd() and let the return do it's work, I get the error.
The redirect() helper function is used to send a redirect 301 response from the server, what you want instead is to return a view like so
public function show(account $account)
{
$account = account::where(['AccID' => $account])->get();
return view('user.show', compact('account'));
}
I'm displaying user profiles on a PHP website using usernames as part of the URL that links to the given user profile.
I can achieve this through a controller, the ProfileController, but the URL will look like this thewebsite.com/profile/show_profile/ANYUSERNAMEHERE
What i want is something similar to Facebook, where the username is appended just after the base URL:
https://www.facebook.com/zuck
I tried passing a variable to the Index function (Index()) of the home page controller (IndexController), but the URL becomes thewebsite.com/index/ANYUSERNAMEHERE and the base url thewebsite.com throws an error:
Too few arguments to function IndexController::index(), 0 passed and exactly 1 expected.
The home page controller:
<?php
class IndexController extends Controller
{
public function __construct()
{
parent::__construct();
}
// IF LEFT, THE VARIABLE $profile THROWS AN ERROR AT THE BASE URL
public function index($profile)
{
/** AFTER REMOVING THE $profile VARIABLE ABOVE AND THE 'if'
* STATEMENT BELOW, THE ERROR THROWN AT THE BASE URL VANISHES AND
* THE WEBSITE GOES BACK TO IT'S NORMAL STATE. THIS CODE WAS USED
* TRYING TO RENDER THE URL thewebsite.com/ANYUSERNAMEHERE BUT IT
* ONLY WORKS WITH thewebsite.com/index/ANYUSERNAMEHERE
*/
if (isset($profile)) {
$this->View->render('profiles/show_profile', array(
'profiles' => ProfileModel::getSelectedProfile($profile))
);
} else {
$this->View->render('index/index', array(
'profiles' => ProfileModel::getAllProfiles()));
}
}
The profile controller:
<?php
class ProfileController extends Controller
{
public function __construct()
{
parent::__construct();
Auth::checkAuthentication();
}
public function index()
{
$this->View->render('profiles/index', array(
'profiles' => ProfileModel::getAllProfiles())
);
}
public function show_profile($profile)
{
if (isset($profile)) {
$this->View->render('profiles/show_profile', array(
'profiles' => ProfileModel::getSelectedProfile($profile))
);
} else {
Redirect::home();
}
}
}
I was expecting the base URL to pass the argument (the username) to the IndexController's Index($profile) function, but the webpage throws an error and the expected result is being displayed from the wrong URL: thewebsite.com/index/ANYUSERNAMEHERE
You would need to use a router based on regular expressions, like FastRoute, or Aura.Router.
For example, with FastRoute you'd define and add a route to the so-called route collector ($r) like this:
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
// The /{profile} suffix is optional
$r->addRoute('GET', '[/{profile}]', 'handler');
});
where handler is just a generic name for a customizable route handler in form of a callable. For example, if you'd additionally use the PHP-DI/Invoker library, the route handler ('handler') could look like one of the following callables (at least):
[ProfileController::class, 'show_profile']
'ProfileController::show_profile'
So the complete route definition would be like:
$r->addRoute('GET', '[/{profile}]', [ProfileController::class, 'show_profile']);
$r->addRoute('GET', '[/{profile}]', 'ProfileController::show_profile');
The placeholder name (profile) corresponds to the name of the parameter of the method ProfileController::show_profile:
class ProfileController extends Controller {
public function show_profile($profile) {
...
}
}
Even though the URL would look like you want it, e.g. thewebsite.com/zuck, I imagine that the placeholder {profile} of the above route definition would come in conflict with the fixed pattern parts defined in other route definitions, like /books in:
$r->addRoute('GET', '[/books/{bookName}]', 'handler');
So I suggest to maintain a URL of the form thewebsite.com/profiles/zuck, with the route definition:
$r->addRoute('GET', '/profiles/{profile}', 'handler');
I also suggest to read and apply the PHP Standards Recommendations in your code. Especially PSR-1, PSR-4 and PSR-12.
I am using Laravel AdminLTE and I have it all configured, there is just one part I do not understand. I made my route like so:
Route::get('/admin/painlevel', function () {
return view('painlevel');
});
and I have this method in app/Http/Controllers/v1/PainLevelController.php
public function index()
{
return PdTpainlevel::select('pkpainlevel as id', 'painlevel_name as name')->get();
}
How would I call that method and display the data in my painlevel view?
Your current route is merely returning the view('painlevel') directly.
You need to update your route to:
Route::get('/admin/painlevel', 'V1\PainLevelController#index');
In your controller:
public function index()
{
$data = PdTpainlevel::select('pkpainlevel as id', 'painlevel_name as name')->get();
return view('painlevel', compact('data'));
}
You might want to start glancing through the documentations, start with Route, Controller and View
route create like this
Route::get('/administrator', 'administrator\LoginController#index');
and controller create like this
public function index()
{
$data['title']="Admin | DashBoard";
$data['name']="Dilip Singh Shekhawat";
view('administrator/menu_bar',$data);
return view('administrator/dashboard',$data);
}
its working .
So I have a Laravel Controller (MainController.php) with the following lines:
...
public function _settings_a(){
return view('_settings_a');
}
public function _settings_b(){
return view('_settings_b');
}
public function _settings_c(){
return view('_settings_c');
}
public function _settings_d(){
return view('_settings_d');
}
public function _staff_a(){
return view('_staff_a');
}
public function _staff_b(){
return view('_staff_b');
}
public function _staff_c(){
return view('_staff_c');
}
...
And my routes.php is as follows:
Route::any('_staff_a''MainController#_staff_a');
Route::any('_staff_b''MainController#_staff_b');
...
etc.
It seems there are a LOT of lines and a LOT of things to change if I change my mind...
I was wondering if I can have some regex in routes.php and an equivalent regex in MainController.php for handling routes that begin with an underscore (_)?
Can any Laravel experts share some tips/suggestions? I'm quite new to the framework.
Sure - just add it as a parameter. E.g. like this:
Route::any('_staff_{version}', 'MainController#_staff');
public function _staff($version) {
return view('_staff_'.$version);
}
I don't think you need to mess with regex. You can use implicit controllers Route::controller() which isn't the BEST solution, but will do what I think you are wanting.
So instead of
Route::any(..)
you can do
Route::controller('url', 'MainController');
So your route to whatever 'url' is will send you to this controller. Follow that with a '/' and then add whichever method in the controller you want to call.
Here is an example:
My url: 'http://www.example.com/users'
// routes.php
Route::controller('users', UserController');
// UserController.php
public function getIndex()
{
// index stuff
}
Now I send a request like: http://www.example.com/users/edit-user/125
// UserController.php
public function getEditUser($user_id)
{
// getEditUser, postEditUser, anyEditUser can be called on /users/edit-user
// and 125 is the parameter pasted to it
}
Doing it this way should allow you to be able to just send a request (post or get) to a url and the controller should be able to call the correct method depending on the url.
Here are some more rules about it: http://laravel.com/docs/5.1/controllers#implicit-controllers
I would like to pass variable (that would be service menager) to a build-in helper of zend. Is it possible? To be more clearly:
There is a zend helper called Url, which constructs url's
In this helper I would like to get some data from database, so I need to pass there connection or model (doesn't matter really)
Depends on data get in point 2. I would like to construct my custom link
Well, the thing looks like this: I'm trying to make own custom routing. So in database I have controller, action and it's alias. For example:
Home\Controller\Home | index | myalias
Routing works fine, that means that if I type url:
example.com/myalias
Then Zend will open Home controller and index action. But on whole page I have url's made by Zend build-in Url helper, which looks like this:
$this->url('home', array('action' => 'index'));
So link looks:
example.com/home/index
I would like to change link to
example.com/myalias
without changing links generated by Url helper on whole page. So before helper return url, should check if that url have alias, and if so then should return that alias exept regular url.
In Module.php of the module where you have he helper class file, write the following -
//use statements
class Module {
//public function getAutoloaderConfig() { [...] }
//public function getConfig() { [...] }
public function getViewHelperConfig() {
return array(
'factories' => array(
'Url' => function ($sm) {
$locator = $sm->getServiceLocator();
$viewHelper = new View\Helper\Url;
//passing ServiceLocator to Url.php
$viewHelper->setServiceLocator($locator); //service locator is passed.
return $viewHelper;
},
),
);
}
}
Now in the Url.php, we need a function setServiceLocator() and getServiceLocator().
//use statements
class Url {
public $serviceLocator;
public function getServiceLocator() {
return $this->serviceLocator;
}
public function setServiceLocator($serviceLocator) {
if($this->serviceLocator == null)
$this->serviceLocator = $serviceLocator;
return;
}
}
I hope it helps.