I am building a store so i could learn laravel. Like most stores, users can add items to a cart but cannot checkout until they register. How do i have the same route return a user name when authorized and a nothing when an authorized. This seemed very easy to me at first:
@if(Auth::guest())
Nothing || or login/register buttons
@else
{{ Auth::user()->name }}
@endif
That works well when you have content that should only be visible to loyal users but for a store, you need users to see whats there to offer.
The problem is that, in my home controller, i need to add middleware auth in the constructor function so that Route::get('/',HomeController@index);
returns a view and in the view use @if(Auth::guest()) ...
, but adding this middleware means this route is not accessible if the user is not Authenticated and without it you get this issue.
So how do i have the same root route with Authenticated user data(if authenticated)
without blocking the route from unauthenticated users?
If i am understanding what you are asking (Though i believe i dont quite fully get what you mean).
You want to use the Auth::user() or Auth::check() throughout your views? This should be available out of the box especially when you have used php artisan make:auth.
One way to achieve this would be to use view->share() in a service provider on the boot method, This will then make the $user variable or $isSignedIn variable available in all views.
For example in your App\Providers\AppServiceProvider
namespace App\Providers;
use App\User;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->share('isSignedIn', Auth::check());
view()->share('user', Auth::user() ?: new User());
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
If this is not going to help let me know and i can help towards getting the outcome you need.
- Update
On your HomeController can you try:
use App\User;
use Illuminate\Support\Facades\Auth;
and in your index() method can you add:
if(Auth::user()){
$user = Auth::user();
}else{
$user = new User();
// or you can use:
$user = Auth::guest();
// If you use $user = Auth::guest() you can remove the Use App\User;
}
return view('home', compact('user'));
See if that does anything for you?