Protected routes error in laravel 5.2 - php

I have this protected route to be accessed only when the user is authenticated:
Route::get('/checkout', [
'middleware' => 'auth',
'uses' => 'Front#checkout'
]);
and the other routes are:
// Authentication routes...
Route::get('auth/login', 'Front#login');
Route::post('auth/login', 'Front#authenticate');
Route::get('auth/logout', 'Front#logout');
// Registration routes...
Route::post('/register', 'Front#register');
And my controller is:
<?php
namespace App\Http\Controllers;
use Request;
use Redirect;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class Front extends Controller {
public function register() {
if (Request::isMethod('post')) {
User::create([
'name' => Request::get('name'),
'email' => Request::get('email'),
'password' => bcrypt(Request::get('password')),
]);
}
return Redirect::away('auth/login');
}
public function authenticate() {
if (Auth::attempt(['email' => Request::get('email'), 'password' => Request::get('password')])) {
return redirect()->intended('/checkout');
} else {
return view('auth/loginerror', array('title' => 'Welcome', 'description' => '', 'page' => 'home'));
}
}
public function login() {
return view('auth/login', array('page' => 'home'));
}
public function checkout() {
return view('contactme', array('page' => 'home'));
}
public function logout() {
Auth::logout();
return Redirect::away('auth/login');
}
}
how is this error in the route?
NotFoundHttpException in RouteCollection.php line 161:

Related

laravel 5.5 return redirect route not working

I'm having a strange issue with my laravel app .
I have a route defined as :
web.php
Route::get('/', ['as' => '/', 'uses' => 'LoginsController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginsController#postLogin']);
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginsController#getLogout']);
Route::get('/dashboard','DashboardController#dashboard')->name('dashboard');
});
In a controller , i'm trying to redirect to this route
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginsController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web'))
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postLogin(Request $request)
{
$auth = Auth::guard('web')->attempt([
'username' => $request->username,
'password' => $request->password,
'active' => 1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
Where I am typing http://localhost:8000 in address bar of browser. I see.

Laravel routes going to wrong route

I do not understand the following problem.
Here are me routes:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
I can not create a new event, because when I click on the 'New Event' button, it uses EventController#view instead of EventController#newEvent.
Here is the EventController:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\EventModel;
class EventController extends Controller
{
public function index()
{
$events = EventModel::all();
return \View::make('event/index')->with('events', $events);
}
public function view($id)
{
return \View::make('event/view')
->with('event', EventModel::find($id));
}
public function newEvent()
{
dd("dd");
return \View::make('event/create');
}
public function create()
{
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->action('EventController#newEvent')
->withErrors($validator)
->withinput();
}
else
{
EventModel::create(array(
'title'=>Input::get('title'),
'start'=>Input::get('start'),
'end'=>Input::get('end'),
'userID'=>\Auth::user()->id,
));
//Session::flash('message', 'New event has been created!');
flash()->overlay('New event has been created!', 'Success');
return redirect()->back();
}
}
public function edit($id)
{
return \View::make('event/edit')
->with('event', EventModel::find($id));
}
public function update()
{
$event = EventModel::find(Input::get('event_id'));
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->back()
->withErrors($validator)
->withinput();
}
else
{
$event->title = Input::get('title');
$event->start = Input::get('start');
$event->end = Input::get('end');
$event->save();
//Session::flash('message', 'Successfully updated!');
flash()->overlay('Event has been sucessfully updated!', 'Success');
return redirect()->back();
}
}
public function destroy()
{
$id = Input::get('event_id');
dd("$id");
}
}
Why does this problem occur?
You have to sort your routes because laravel checks the order of the routes.
Try:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Laravel route checks in the order they were defined.
event/new_event and event/{id} both have same route structure and so it is going to view action.
Change the order -
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));

Custom Login System In Laravel

I create a customized login system in Laravel.
This is my controller:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
class Front extends Controller
{
public function register()
{
if (Request::isMethod('post')) {
User::create([
'name' => Request::get('name'),
'email' => Request::get('email'),
'password' => bcrypt(Request::get('password')),
]);
}
return Redirect::away('login');
}
public function authenticate()
{
if (Auth::attempt(['email' => Request::get('email'), 'password' => Request::get('password')])) {
return redirect()->intended('checkout');
} else {
return view('login', array('title' => 'Welcome', 'description' => '', 'page' => 'home'));
}
}
public function login()
{
return view('auth/login', array('page' => 'home'));
}
public function checkout()
{
return view('/aboutme', array('page' => 'home'));
}
}
And the routes are:
// Authentication routes...
Route::get('auth/login', 'Front#login');
Route::post('auth/login', 'Front#authenticate');
Route::get('auth/logout', 'Front#logout');
// Registration routes...
Route::post('/register', 'Front#register');
Route::get('/checkout', [
'middleware' => 'auth',
'uses' => 'Front#checkout'
]);
The error i am getting is:
FatalErrorException in Front.php line 12: Class
'App\Http\Controllers\Request' not found
You need to import Request. Add this to the top of your controller:
use Request;
By the way you will need to do this for the Redirect facade as well.
Your imports should look like this:
use Auth;
use Request;
use Redirect;
use App\Http\Controllers\Controller;
Try the following as it seems like you are not using Request specific namespace in your Front Controller:
use Illuminate\Http\Request;

laravel 5.2 - Auth::user()->username is empty

If I use Auth::user()->username in a Blade file laravel returns me an empty String but Auth::user()->email is filled. I use my own AuthController and my Login,Register and Logout work perfectly but I can't get the username.
Routes.php
<?php
Route::group(['middleware' => ['web']] , function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::group(['middleware' => ['web','guest']], function () {
Route::auth();
#Sign up Routes
Route::get('/signup', function () {
return view('auth.signup');
})->name('auth.signup');
Route::post('/signup', 'AuthController#signup');
#Sign in Routes
Route::get('/signin', function () {
return view('auth.signin');
})->name('auth.signin');
Route::post('/signin', 'AuthController#signin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::auth();
#Sign out Routes
Route::get('/signout', 'AuthController#signout')->name('auth.signout');
});
And my custom Auth Controller is:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request) {
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|min:2|max:20',
'password' => 'required|min:6'
]);
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('home');
}
public function signin(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('flash-message','We can not sign you in with this data!');
}
return redirect()->route('home');
}
public function signout() {
Auth::logout();
return redirect()->route('home');
}
}
Maybe someone can help me
.
Note:
I added the username into User.php under the filled array.
Most likely you are missing username in $fillable of your User model.
The create method only accept fields coming from $fillable.
Please edit your User model like this:
protected $fillable = [
'email', 'username', 'password',
];
Only $fillable fields insert by Create method.

ErrorException Argument 1 passed to (Laravel 5.2)

So i'm trying to "like" a status and when I do, I get this error in return
ErrorException in User.php line 107:
Argument 1 passed to SCM\User::hasLikedStatus() must be an instance of Status, instance of SCM\Status given, called in C:\xampp\htdocs\app\Http\Controllers\StatusController.php on line 66 and defined
When I remove "use Status;" from my User.php the function works and it updated my database with the like ID. Could this be because I linked my status's public function like "SCM\Status"?
Routes.php
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
Route::get('/login', function () {
return view('auth/login');
});
Route::get('/register', function () {
return view('auth/login');
});
/**
*User Profile
*/
Route::get('/user/{username}', [
'as' => 'profile.index', 'uses' => 'ProfileController#getProfile'
]);
Route::get('/profile/edit', [
'uses' => 'ProfileController#getEdit', 'as' => 'profile.edit', 'middleware' => ['auth'],
]);
Route::post('/profile/edit', [
'uses' => 'ProfileController#postEdit', 'middleware' => ['auth'],
]);
Route::get('/settings', [
'uses' => 'ProfileController#getEdit', 'as' => 'layouts.-settings', 'middleware' => ['auth'],
]);
Route::post('/settings', [
'uses' => 'ProfileController#postEdit', 'middleware' => ['auth'],
]);
/**
* Friends
*/
Route::get('/friends', [
'uses' => 'FriendController#getIndex', 'as' => 'friend.index', 'middleware' => ['auth'],
]);
Route::get('/friends/add/{username}', [
'uses' => 'FriendController#getAdd', 'as' => 'friend.add', 'middleware' => ['auth'],
]);
Route::get('/friends/accept/{username}', [
'uses' => 'FriendController#getAccept', 'as' => 'friend.accept', 'middleware' => ['auth'],
]);
/**
* Statuses
*/
Route::post('/status', [
'uses' => 'StatusController#postStatus', 'as' => 'status.post', 'middleware' => ['auth'],
]);
Route::post('/status/{statusId}/reply', [
'uses' => 'StatusController#postReply', 'as' => 'status.reply', 'middleware' => ['auth'],
]);
Route::get('/status/{statusId}/like', [
'uses' => 'StatusController#getLike', 'as' => 'status.like', 'middleware' => ['auth'],
]);
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', [
'as' => 'welcome', 'uses' => 'WelcomeController#index'
]);
Route::get('/profile', function () {
return view('layouts/-profile');
});
Route::get('profile/{username}', function () {
return view('layouts/-profile');
});
Route::get('/home', 'HomeController#index');
});
/**
* Search
*/
Route::get('/search', [
'as' => 'search.results', 'uses' => 'SearchController#getResults'
]);
User.php (model)
<?php
namespace SCM;
use Status;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $primaryKey = 'id';
public function getAvatarUrl()
{
return "http://www.gravatar.com/avatar/{{ md5 ($this->email)}}?d=mm&s=40 ";
}
public function statuses()
{
return $this->hasMany('SCM\Status', 'user_id');
}
public function likes()
{
return $this->hasMany('SCM\Like', 'user_id');
}
public function friendsOfMine()
{
return $this->belongsToMany('SCM\User', 'friends', 'user_id', 'friend_id');
}
public function friendOf()
{
return $this->belongsToMany('SCM\User', 'friends', 'friend_id', 'user_id');
}
public function friends()
{
return $this->friendsOfMine()->wherePivot('accepted', true)->get()->
merge($this->friendOf()->wherePivot('accepted', true)->get());
}
public function friendRequests()
{
return $this->friendsOfMine()->wherePivot('accepted', false)->get();
}
public function friendRequestsPending()
{
return $this->friendOf()->wherePivot('accepted', false)->get();
}
public function hasFriendRequestPending(User $user)
{
return (bool) $this->friendRequestsPending()->where('id', $user->id)->count();
}
public function hasFriendRequestReceived(User $user)
{
return (bool) $this->friendRequests()->where('id', $user->id)->count();
}
public function addFriend(User $user)
{
$this->friendOf()->attach($user->id);
}
public function acceptFriendRequest(User $user)
{
$this->friendRequests()->where('id', $user->id)->first()->pivot->update([
'accepted' => true,
]);
}
public function isFriendsWith(User $user)
{
return (bool) $this->friends()->where('id', $user->id)->count();
}
public function hasLikedStatus(Status $status)
{
return (bool) $status->likes
->where('likeable_id', $status->id)
->where('likeable_type', get_class($status))
->where('user_id', $this->id)
->count();
}
}
Status.php (model)
<?php
namespace SCM;
use Illuminate\Database\Eloquent\Model;
class Status extends Model
{
protected $table = 'statuses';
protected $fillable = [
'body'
];
public function user()
{
return $this->belongsTo('SCM\User', 'user_id');
}
public function scopeNotReply($query)
{
return $query->whereNull('parent_id');
}
public function replies()
{
return $this->hasMany('SCM\Status', 'parent_id');
}
public function likes()
{
return $this->morphMany('SCM\Like', 'likeable');
}
}
Likes.php (model)
<?php
namespace SCM;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
protected $table = 'likeable';
public function likeable()
{
return $this->morphTo();
}
public function user ()
{
return $this->belongsTo('SCM\User', 'user_id');
}
}
StatusController.php
<?php
namespace SCM\Http\Controllers;
use Flash;
use Auth;
use Illuminate\Http\Request;
use SCM\User;
use SCM\Status;
class StatusController extends Controller
{
public function postStatus(Request $request)
{
$this->validate($request, [
'status' => 'required|max:1000',
]);
Auth::user()->statuses()->create([
'body' => $request->input('status'),
]);
return redirect()->route('welcome')->with('info', 'Status posted.');
}
public function postReply(Request $request, $statusId)
{
$this->validate($request, [
"reply-{$statusId}" => 'required|max:1000',
], [
'required' => 'The reply body is required.'
]);
$status = Status::notReply()->find($statusId);
if (!$status) {
return redirect()->route('welcome');
}
if (!Auth::user()->isFriendsWith($status->user) && Auth::user()->id !==
$status->user->id) {
return redirect()->route('welcome');
}
$reply = Status::create([
'body' => $request->input("reply-{$statusId}"),
])->user()->associate(Auth::user());
$status->replies()->save($reply);
return redirect()->back();
}
public function getLike($statusId)
{
$status = Status::find($statusId);
if (!$status) {
return redirect()->route('welcome');
}
if (!Auth::user()->isFriendsWith($status->user)) {
return redirect()->route('welcome');
}
if (Auth::user()->hasLikedStatus($status)) {
return redirect()->back();
}
$like = $status->likes()->create([]);
Auth::user()->likes()->save($like);
return redirect()->back();
}
}
Remove the use statement for Status in your Users.php. When you're doing that, you're actually trying to use \Status. Your file is already in the namespace SCM, so you don't need any use statement to use classes in the same namespace.
So in your method definition you're saying you want an instance of \Status as your parameter, but are passing in a SCM\Status.

Categories