Creating user profile tables that are publicly accessible in Laravel 5.8 - php

I am having some trouble with my application when trying to create the user profiles. Here is the issue:
I am trying to create a view called userprofile.blade.php which will output any given users profile (based on id or username...doesn't really matter right now). Each profile page will show name, description, location, profile pic, and the given users posts. I used Laravel's Make:auth command to create the necessary authentication, customized the authentication forms, and then migrated all the columns I needed in my database.
My create and update methods work just fine (registering new users and updating their information). All the information is saved correctly in the database. However, I can only access it in my views with {{Auth::user()->}}. Whenever I try to use the Model in my Controller to access the data I need, it doesn't work. It seems to me as though I need to separate Laravel's default 'User' model with a custom model which I would call 'Account' or something along those lines.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Recipe;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => [
'index', 'show'
]]);
}
public function index(){
$user = User::find($id);
return view('user.userprofile')->with('user');
}
I only included the index method from my UserController to keep it simple. It breaks down and tells me that 'id' in $user = User::find($id); is an undefined variable. That tells me that it isn't accessing my database table.
My question is, should I create a new fresh model that isn't mixed up with authentication to handle all the user profile information? If so, how do I access my current database table 'users' from this new model?
Please let me know if I need to clarify things for you guys. I'm not very experienced and I understand if my question is fuzzy. Thanks so much for your time!! I really appreciate any help I can get!

Hello and welcome to developing with Laravel!
You're on the right track - you need to identify which user's profile you're viewing, retrieve it from the database, and pass it to the Blade view. You don't need a new model or anything, though! Just need to complete what you've started.
You should start by defining a route parameter in your route, that will capture the dynamic data you want from the URL. Let's use the numeric ID for now. If you want a URL that looks like example.com/user/439, your route should look something like Route::get('user/{id}', 'UserController#index');.
Once you have that, the id parameter will get passed to your controller's method. Define it as a method parameter, and it'll be usable: public function index($id) { ... }
I think you can take it from there. :)

Related

Final Route URL Change Laravel 5.5

I am working on a school project. while working on a schools detail page I am facing an issue with the URL. My client needs a clean URL to run AdWords. My school detail page URL: http://edlooker.com/schools/detail/4/Shiksha-Juniors-Ganapathy. But he needs it like http://edlooker.com/Shiksha-Juniors-Ganapathy. If anyone helps me out it will be helpful, thanks in advance.
You need to define this route after all routes in your web.php (if laravel 5.x) or in routes.php (if it is laravel 4.2).
Route::get('{school}','YourController#getIndex');
And your controller should be having getIndex method like this,
public function getIndex($school_name)
{
print_r($school_name);die; // This is just to print on page,
//otherwise you can write your logic or code to fetch school data and pass the data array to view from here.
}
This way, you don't need to use the database to get URL based on the URL segment and you can directly check for the school name in the database and after fetching the data from DB, you can pass it to the school details view. And it will serve your purpose.
Check Route Model Binding section in docs.
Customizing The Key Name
If you would like model binding to use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model:
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
In this case, you will have to use one front controller for all requests and get data by slugs, for example:
public function show($slug)
{
$page = Page::where('slug', $slug)->first();
....
}
Your route could look like this:
Route::get('{slug}', 'FrontController#show');

Laravel: simplest/right way to save a new step after login?

I'm having my first interaction with the core laravel code so I want to be careful not to break anything.
In my project, my users also correspond to person records (via user->person_id), so I have a get_person_from_user() function that takes the \Auth::user() (conveniently accessible anywhere) and returns the person object, so I can grab the person record for the authenticated user from any controller and pass it to a view.
The problem: there's a piece of data from the person record that I'd like to include in a nav partial in my default blade view (which gets extended by a bunch of different views), so it's the one case where I'm not going through a controller first. I'm unclear on how I can make the logged in user's person record available here. Any suggestions?
I think I need to add some step after the user logs in, to save the person record (globally? in the session?) so it's generally accessible. The login stuff happens in AuthenticatesUsers.php, and reading around it sounds like I'll want to add an override of postLogin to my AuthController.
But I tried copying that function from AuthenticatesUsers.php into my AuthController (not adding anything else to it yet), and AuthController gives me a new error when I try to log in:
ReflectionException in RouteDependencyResolverTrait.php line 81:
Class App\Http\Controllers\Auth\Request does not exist
Any advice on a good way to go about accessing the person object for the authenticated user, when I don't have a controller to pass it along?
You can setup the correct relationship on the User model to Person model.
public function person()
{
return $this->belongsTo(Person::class);
}
Then you can do:
Auth::user()->person;
For having a variable available to a particular view you can use a View Composer. (You can create and register a Service Provider and add this to the register method.) Potentially something like this:
view()->composer('someview', function ($view) {
if ($user = Auth::user()) {
$somevar = $user->person->somevar;
} else {
$somevar = null; // or some default
}
$view->with('somevar', $somevar);
});
If this view is also used in a scenario where someone doesn't have to be authed you will want to check if Auth::user() is null before trying to use the relationship.
Laravel Docs - Views - View Composers
I suggest you to use Eloquent relation
User.php
public function person()
{
return $this->belongsTo('NAMESPACE_TO_YOUR_MODEL\Person'); //also you can specify FK, more info in docs
}
then you can access Auth facade in your view
Auth::user()->person

Laravel Different Route Same Controller

I'm building an API for user and admin.
Got stuck at edit user profile routing.
on admin route i use Route::resource('user', 'UserController')
on user route i use Route::get('profile', 'UserController#show')
At the show method Laravel default has
public function show($id)
{
}
the different between them is on admin I can use /id but on user i check their token from middleware and merge the request to get their user_id so there is no need for the API to use profile/{id}.
The question is how can I use the same method but there is an argument to fill and the route still /profile?
One of my solution is :
public function show($id){
if ($request->has('user_id')):
$id = $request->query('user_id');
endif;
}
It working but when i read the code, it's really redundant always checking it and replace the id.
Just place the request object as a parameter in your controller and get the input from the request object when you use your user route.
Thanks

Login with Facebook using Sentry in Laravel

I am facing a problem as the one posted here
The problem is this piece of code
$profile = $user->profiles()->save($profile);
which results in this error
Call to undefined method Illuminate\Database\Query\Builder::profiles()
I tried to do what was suggested here
but it didn't work for me. It seems the problem has been solved in a link provided which no longer works.
I wrote my question briefly since the same question has been asked by the user in the link I gave. I will appreciate any help. Thanks
Sentry provides their own User model. If you would like to add relationships to the User, you will need to extend Sentry's User model and update the Sentry config to point to your new User model.
First, create your User model which extends the Sentry User model:
<?php
use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;
class User extends SentryUserModel
{
public function profiles()
{
return $this->hasMany('Profile');
}
}
Next, update the Sentry config to look at your User model instead of the default Sentry User model. To do this, publish the Sentry config file:
php artisan config:publish cartalyst/sentry
Once published, open the app/config/packages/cartalyst/sentry/config.php file. Update the 'users'.'model' value to use your new User model. For example:
'model' => 'User', // assumes non-namespaced custom User model
Sentry will now use your custom User model created above, with the defined relationships.

Laravel 5 new auth: Get current user and how to implement roles?

I am currently experimenting with the new Laravel 5 and got the authentication to work (register/login).
To get the authenticated user in my controller I currently inject Guard into the controller action:
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
class ClientController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Guard $auth)
{
return view('client.index', ['user' => $auth->user()]);
}
...
First Question: Is this the recommended way?
Second Question: How would I go about implementing some kind of roles/permissions? Something like client.edit, client.add, ... Does Larval 5 offer some kind of convenience here?
How would I set the necessary role/permission for a route/controller action?
I am thinking that I might need to write my own middleware for that. Any suggestions on how to approach the problem?
After spending some more time on Laravel 5 I can an answer my own question:
Is injecting Guard the recommended way? No: If you need to access Auth in your view, you can do so already like this:
#if( Auth::check() )
Current user: {{ Auth::user()->name }}
#endif
This uses the Auth facade. A list of all available facades is in config/app.php under aliases:
What if I need Auth in my controller? Injecting an instance of Guard like shown in the question works, but you don't need to. You can use the Auth facade like we did in the template:
public function index()
{
if(\Auth::check() && \Auth::user()->name === 'Don') {
// Do something
}
return view('client.index');
}
Be aware that the \ is needed before the facade name since L5 is using namespaces.
I want to have permissions/roles using the new auth mechanism in L5: I implemented a lightweight permission module using the new middleware, it is called Laraguard. Check it out on Github and let me know what you think: https://github.com/cgrossde/Laraguard
UPDATE: For the sake of completeness I want to mention two more projects. They provide everything you need to save roles and permissions in the DB and work perfectly together with Laraguard or on their own:
https://github.com/caffeinated/shinobi
https://github.com/romanbican/roles
If you want make your own custom authentification, you need to keep the User model from Laravel 5 with all the dependency. After you will be able to login your user in your controller. Dont forget to put (use Auth;) after the namespace of your controller.

Categories