Trying to put in the url with laravel - php

So I'm trying to build this application where users have their usernames in the domain name ( domain.com/hisusername for example) and this is what I did, so this is my route
Route::group(['prefix' => '/{username}'], function($username){
Route::get('/', 'UserController#UserProfile');
});
And my controller
public function UserProfile($username){
$user = User::where('username', $username)->first();
if (!$user) {
abort(404);
}
return view('pages.profile')
->with('user', $user);
}
It works fine the problem is when I try to add another route it gets confused with a username and it returns a 404 page, how can I fix that please?

Laravel renders routes from top to bottom. Often when I encounter this problem it's because I need to put my 'catch-all' routes below all the others.
That being said, I would strongly suggest doing something like domain.com/u/user instead to avoid conflicts with existing pages.
It may seem like a stretch, but if you ever had a someone with the username 'login' they might never be able to access their account.

Try like this
Route::group(['prefix' => 'user'], function($username){
Route::get('/{username}', 'UserController#UserProfile');
Route::get('/otherinfo', 'UserController#otherinfo');
});
Route::get('/more/other/route', 'OtherController#methodinfo');
in your browser it will display like. sample.com/user/yourUsername

Okay it's seem very easy :
Route::get('/{username}', ['uses' => 'UserController#UserProfile']);
I don't know why you have to use the group prefix? You just need to define a get routes as normal, you controller look good, it should work ! :)

Related

Detect if action is show or edit in Laravel 5.2

I have a middleware that detects if a user owns a tournament.
So, if user want to edit a tournament he doesn't own, he will get a 403.
Thing is I can't make difference between laravel.dev/tournament/1/edit, and laravel.devl/tournament/1
Off course, I could check the "edit" word in URL, but I would prefer other better param...
I tried method param in Request Object, but it is giving me GET for both, so I can't make difference...
Any Idea???
In your case, you can do like this:
$request->route()->getName();
Now you can do your logic based on this.
What about using a different HTTP method for edit, e.g PATCH or PUT and declaring two different routes, something like:
Route::get('laravel.devl/tournament/1', 'TournamentController#showTournament');
Route::put('laravel.dev/tournament/1/edit', 'TournamentController#editTournament');
Then in the TournamentController you can check if the user has rights to edit.
It sounds like you should just use route specific middleware instead of global middleware. See https://laravel.com/docs/master/middleware#assigning-middleware-to-routes. Then you can just do:
Route::get('/tournament/{id}/edit', ['middleware' => ['tournamentOwner'], function () {
//
}]);
Route::get('/tournament/{id}', ['middleware' => [], function () {
//
}]);
If it's a RESTful route, you can just do:
public function __construct()
{
$this->middleware('tournamentOwner', ['only' => ['edit']]);
}

Laravel 5 - Determine if route belongs to user

What I am looking to achieve here is to have the username set as myapp.com/username. I can achieve this by doing:
/*
* Other route logic, containing static-url pages, such as
* myapp.com/login so that it overrides any usernames
*/
Route::get('/{username}', function($username) {
return $username . "'s profile.";
});
However, I also want to include company pages following the same rule. For example, myapp.com/janes-bakery. But I cannot seem to achieve this because Laravel automatically stops searching for routes if it comes across one that returns nothing. Instead it will just throw a 404 page.
I did think that I could use something similar along these lines:
Route::get('/{slug}', ['as' => 'profile', function($slug) {
$company = \App\Models\Company::where('slug', '=', $slug)->get();
if($company->count() > 0) {
return "Company found.";
}
$user = \App\User::where('username', '=', $slug)->get();
if($user->count() > 0) {
return "User found.";
}
abort(404);
}]);
Which works fine, however I feel as though it's bad practice. Besides that, I cannot access suffix routes based on the company/user. For example myapp.com/jane/friends or myapp.com/janes-bakery/services.
Does anybody have any recommendations on how to go about this? I am finding it very hard to think of any solutions. Thank you in advance!
P.S. It is important the URLs have no correlation, e.g. no myapp.com/company/user (or vice versa), myapp.com/company_name_here and myapp.com/users_name_here are two totally separate things.
You can stick with your route and make another route with company/user pattern. You can do it this way.
Create another route with company and user parameter.
Route::get('{company}/{user}', function($company, $user){
dd($company, $user);
});
And you need to put this route above your profile route because, in laravel, the first route present will be processed before the others routes below.

Laravel Routing to Wrong View

I'm working with Laravel 4.2. I have an app that's routing to the wrong view, although the URL is correct. On a button click, it's supposed to route to users.create (UsersController#create), but is instead routing to UsersController#show. The resolved URL is correct, though, and the DOM element has the correct URL listed. Can anyone help me out?
Here is my Routes file:
// Home page
Route::get('/', 'BaseController#index');
// Define User model to pass through routes
Route::model('user', 'User');
// Create custom route for editing a user
Route::get('users/edit/{user}',
array('as' => 'users.edit', 'uses' => 'UsersController#edit'));
// Create custom route for showing a user
Route::get('users/{user}',
['as' => 'users.show', 'uses' => 'UsersController#show']);
// Remaining routes
Route::resource('users', 'UsersController',
array('except' => array('edit', 'show')));
Here is my UsersController with the two functions in question:
class UsersController extends \BaseController {
protected $user;
public function create()
{
return View::make('users/create');
}
public function show($user)
{
return View::make('users/show', ['user' => $user]);
}}
And here are the relevant results from php artisan routes:
GET:HEAD users/{user} users.show UsersController#show
GET:HEAD users/create users.create UsersController#create
Thanks for your help!
Edit:
The answer to the problem was to simply re-order the routes so that the resource is defined first. I was aware that Laravel grabs the first route that matches a URI, but I still don't understand why a route that isn't passed a user object would select a route defined as users/{user}. Furthermore, I was accessing the route via link_to_route(), that is to say, by name. Why would Laravel pick a different route from the one I explicitly named?
I suppose these questions are beyond the scope of the initial question, but I would greatly appreciate further explanation from someone. Problem solved!
The first thing that jumps out at me is there is no route for "create". There is the "restful" controller, but maybe you want to just try putting the route in. I'm slightly uncomfortable using restful routes when serving html. In the project i'm working on i've been trying to preserve those for data/json transmission, in order to support outside api action.
I think your routes setup recognizes create as {user} in user/{user}, thus redirect to user/show/create as your "custom route for showing a user" setup.
You may have to avoid getting string variable right after users/ route.

Laravel sub-domain routing without passing variable to URL::route()

In a Laravel 4 app, i'm using subdomain routing around a bunch of Route::resource's like this:
Route::group(['domain' => '{account}.my.app'], function()
{
Route::group(['before' => 'auth'], function($account)
{
Route::resource('organisations', 'OrganisationsController');
Route::resource('clients', 'ClientsController');
Route::resource('domains', 'DomainsController');
});
});
In my auth filter i'm doing the following:
Route::filter('auth', function($route)
{
// you could now access $account in a controller if it was passed as an argument to the method
$account = $route->getParameter('account');
// share account variable with all views
View::share('account', $account);
// Auth::guest Returns true if the current user is not logged in (a guest).
if (Auth::guest()) return Redirect::guest('login');
});
Within my views I can now access $account, but if I want a call to URL::route() to be correct I have to manually pass the account variable, like URL::route('clients.show',['account' => $account]) otherwise it generates URLs like %7Baccount%7D.my.app.
This is a bit of a pain and doesn't seem that elegant, is there any other or better way to achieve this? I guess I could create my own route helper to use instead of the built-in one.
However, I also do redirects with Redirect::route() within controllers so I would also need to make updates here.
EDIT
As suggested in the comments it may be that extending the Route API is the best approach here. Does anyone have any suggestions how this should be done?
Thanks.

Laravel 4 Resource Routes and Authentication

I'm not sure of the terminology I should be using so please bear with me, hopefully if I haven't got this right, someone might be able to tease the right question out!
ok.. so I have
Route::resource('gameworlds', 'GameworldsController');
This is fine. There are views for create, edit, index and show as you would expect and they all work fine. What I would like to do is only allow access to the "create" part when a user is logged in.
For example.. I have another route in my routes.php file:
Route::get('dashboard', array('before' => 'auth', function()
return View::make('dashboard/index');
}));
This works as expected, but I don't really understand how I can put similar code in the resource route for the "create" part only. Can someone explain that part to me please?
Many thanks.
DS
Well you don't need a filter, but instead you can use the Auth check method to check if user is logged in or not:
if (Auth::check()) { //Logged in }
In your controller method to make sure the user is logged in, and if he isn't you can do a redirect, like:
return Redirect::to('user/login');
However if you want to use a filter you could use the beforeFilter method in the __construct of your controller, like this:
public function __construct()
{
$this->beforeFilter('auth', array('on' => array('create')));
}

Categories