authentication,laravel-5,laravel-routing , Laravel 5 Auth for Restful Resource Controllers to restrict resource to logged in user

Laravel 5 Auth for Restful Resource Controllers to restrict resource to logged in user


Tag: authentication,laravel-5,laravel-routing

I have a pretty basic RESTful address manager. I have user accounts setup with user login all based on Auth and am in the process of integrating entrust but that's beyond the scope of this. For now, I simply want to restrict access to my AddressController to users who are logged in. I'm able to do this on a route using:

Route::get('profile', ['middleware' => 'auth', 'uses' => '[email protected]']);

However if I try this on my RESTful resource as follows it doesn't work - I don't get an error, but the un-authenticated user can still access the resource.

Route::resource('addresses', 'AddressController', ['middleware' => 'auth']);


Try grouping your resources that should use a specific middleware:

Route::group(['middleware' => 'auth'], function(){
    Route::resource('addresses', 'AddressController');

Only you know how your scenario is, but another way to run filters in resources is to call to needed middlewares in the resource's constructor like:

class AddressController extends Controller {

public function __construct()


Change extends(layout) dynamically in laravel 5

I have been trying to change layout dynamically in laravel by just passing a variable in @extends('default1.master') to $var = default2 @extends('$var.master') possibly @extends($var.'.master') tried a lot but unable to find a solution all I get is error in my syntax or view not found....

Laravel 5 MethodNotAllowedHttpException

I am using a form with PATCH method and I have a button link(since i already have a submit button and using same form for both store and update) as <a class="btn btn-default" href="{{ URL::to( 'pages/edit/' . $vehicle -> id) }}">EDIT</a> And my route is Route::patch('/pages/edit/{id}', ['uses' => '[email protected]']); Controller...

Laravel 5 - How to get Auth user ID in controller, retrieve user data and display that data in view

New to the Laravel 5 framework (and OOP), I want to create a view where a user can view/edit his own user profile when he's logged in. What would be the syntax to get Auth user ID in controller, retrieve user data (from DB) and display that data in the...

Sync element to a child on Laravel

My Shema database is User Table id login parent Sign Table id name user_id (Sign owner) Pivot table user_sign id user_id sign_id My User model contain public function signs() { return $this->belongsToMany('App\Sign', 'user_sign'); } public function parent(){ return $this->belongsTo('User', 'parent'); } public function children(){ return $this->hasMany('User', 'parent', 'user_id'); } And...

Cannot get parameter value from url in main page

I searched a lot for the issue. But I couldn't find anything related to getting parameter value from get request in app.blade.php file. URL: http://localhost:8000/project/dashboard/1 I want to get this parameter value after user is signed in. Following is the code in AuthController. if ($this->auth->attempt($request->only('email', 'password'))) { return redirect()->route('dashboard', ['id'...

How to enable multiple login tries in forms authentication?

I have a MVC project with forms authentication. Basically it works fine: The user wants to access a controller with Authorize-Attribute and gets redirected to login-page if not authenticated. On redirect the parameter returnUrl gets forwarded as well. However, in case the first try of the login fails, the return...

Update enum column in Laravel migration using PostgreSQL

According to this answer, I have to run a raw query if I want to update an enum in MySQL. But with PostgreSQL, I can't use this query, and enum type for PostgreSQL in Laravel seems strange. Is there any way to update enum in a migration for postgreSQL ?...

python requests with redirection

Trying to authenticate on site, noticed that there were a redirect to Found that there were 302 POST with plain credentials in data form. Copying headers from Chrome can reproduce that in cURL, but still can't reach in requests module. Warning: page is full of russian letters, registration...

Error Hashing + Salt password

Someone can help me to fix this problem: TypeError: can't concat bytes to str I am trying to safely store hash+salt passwords, I think the problem is that my salt is a byte object how can I transform it into a string? Or is there a way to hash it...

Laravel 5: How to add Auth::user()->id through the constructor ?

I can get the ID of the authenticated user like this: Auth::user()->id = $id; Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in...

Getting code from my forked repository

I made a fork from a repository called "chrisbjr/api-guard". the repository latest version is v2.2.2, and I made a release v2.2.3 from my fork. I have my own branch which is dev-fulluth, to get the code from my fork not from the main repo, composer has to contain the below...

Laravel 5.0: Form::select() called twice Eloquent Accessor by select name

Blade template: {!! Form::model($category) !!} {!! Form::select('drinks_id', [...full list...]) !!} {!! Form::close() !!} 'drinks_id' called by Eloquent Accessor: public function getDrinksIdAttribute() { var_dump('get'); return 123; } When Form::select('drinks_id') execute, getDrinksIdAttribute() called twice and print string(3) "get" string(3) "get" from var_dump(). If I write this: {!! Form::model($category) !!} {!! var_dump($category->drinks_id) !!}...

Guzzle error 500

so i have a CURL request that looks like this (and it works): curl -X GET -H "Authorization: Token 1234567890" tried translating it into Laravel Guzzle into something like this: $client = new \GuzzleHttp\Client(['base_uri' => '']); $headers = ['Authorization' => 'Token 1234567890']; $response = $client->get($query_string, $headers); return $response; but...

Laravel 5: Call method in class before the method indicated by the route

I'm sure there's a well documented way to do this in Laravel, I'm just missing it or not understanding what I'm reading. I have an application that uses a token for accessing part of the website, rather than a username or password. That token identifies the job, checks the status...

Loopback Angular SDK response code 401 intercept

I'm using the Angular Loopback SDK and am trying to implement a 401 handler that automatically detects when the user needs to authenticate. Loopback responds to a data request with a 401 and I use that to invoke a login dialog. Basically using the strategy described here - However,...

Laravel 5 not storing checkbox value

We are having a strange issue with Laravel 5 in that it is refusing to store the checkbox value. We are adapting the existing registration form that comes bundled with Laravel 5 and we are adding an optin checkbox but it seems the model does not recognise this as a...

How can I Echoing Data After Checking For Existence in PHP Laravel 5?

I don't have anything store on my user phone field at the moment. <li><i class="md md-phone"></i> {{ $user->phone or 'No Phone' }} </li> So this line should print out No Phone. But instead it print out as blank. I'm confuse. What did I do wrong /forgot ? Is it because...

Cannot insert the value NULL into column 'user_id', table 'dbo.role_user'; column does not allow nulls

I am using Zizaco/Entrust in Laravel 5.0 to apply RBAC and i'm having the following error: Cannot insert the value NULL into column 'user_id', table 'dbo.role_user'; column does not allow nulls. INSERT fails. (SQL: insert into [role_user] ([role_id], [user_id]) values (2, )) I followed all the steps to implement Entrust...

shall I use Spring framework for a performance-critical proxy application? [closed]

I've created a servlet (Tomcat) application which has these functions: It performs HTTP Basic Authentication. It connects to a user and role database. It works as "security facade" for some geodata servers behind It forwards requests after doing some authorization tests In case the response contains XML data, it performs...

Retrieving the Slug from URL for function (Laravel 5)

I'm making an App where a group is created by a user. This user can go to the group page (automated unique slug is created for the groups). My goal is for the member who created the group, to be able to make a invite code for that specific group....

laravel file uploading using json

I am using laravel 5. I have did the following code to post data using json to my controller. But I cannot make file uploading by this manner. e.preventDefault(); $.ajax({ type: 'POST', cache: false, dataType: 'JSON', url: 'tasks', data: $('#my_form').serialize(), success: function(data) { console.log(data); }, }); I have the following...

Simple token-like authentication

Does the following authentication system seem reasonable: Client calls the login end point with a user name and password to the main server. The main server sends this off to another authentication server (which will receive no further mention), which returns a yes/no if this is valid and a user...

Laravel validator vs requests

Hello, I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get. What is the difference between using a request file for validation...

Setting up a second Homestead Laravel app

I've been trying to set up a second Laravel 5 app on my local Homestead space. I have been following the instructions from the official documentation and from this blog. (Although I have had to use the specific ID of the provision in order to get the vagrant provision command...

Laravel 5 form request validation returning forbidden error

I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php. My set up so far: routes.php: Route::post('clinic/{id}', array('as' => 'postUpdateAddress', 'uses' =>...

Bluemix authentication ios8 with google and facebook

I am trying to implement two types of authentication from an iOS8 device in the bluemix platform. I succeeded in adding one type of authentication: google. I am using a ADVANCED MOBILE ACCESS module, and I am at the User Authentication part. It looks from a dashboard like I can...

Connecting to database using Windows Athentication

I would like to use window authentication in my program to connect to my sql server. users already have certain permissions on the SQL server and I would like to leverage that in my program. The way I currently connect to the server is using this connection string. Dim ConnectionString...

Multi service with one-login authentication (Single sign-on)

Single sign-on (SSO) is a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. (from wikipedia) now, I have more web service:...

Laravel GET parameters that include dots cannot be checked

I'm trying to determine whether a parameter is in the URL or not. I use: $request->has('key'); And it's been working properly until now when I have to check wethere I have openid.ns parameter in the URL. If I remove the .(dot) everything works as expected, but: URL: And then...

Laravel 5 Modify Mass Assignment

How I can change the fillable attribute of a model on the fly? For example, I have User model with, protected $fillable = ['name', 'email', 'password'] When updating the user, I want to exclude 'email' from mass assignment so that the email is not changed on update....

Difference between django.contrib.auth.login and django.contrib.auth.views.login

What's the difference to use django.contrib.auth.login or django.contrib.auth.views.login? First in and second in I saw that code and it differs from each other. Same is with some other views, for example 'logout'. As I understand, django.contrib.auth.views.login is used when I want to redefine some parametrs of that view?

How to register global variable for my Laravel application?

I have started with Laravel a few days ago, and today I just installed the vespakoen/menu that seems to be very nice, and probably will work for what I need it. Currently I have installed Laravel 5.1 on my system. The problem I currently have, is where to register my...

How to validate an input date from individual day, month, year input in Laravel 5

I have a user registration form which takes input birth day split in 3 different input fields i.e. day, month, year {!! Form::selectMonth('month', null) !!} {!! Form::selectRange('day', 1, 31, null) !!} {!! Form::selectYear('year', Carbon\Carbon::now()->year, (new Carbon\Carbon('100 years ago'))->year, null) !!} In the backend I have modified the Registrar.php/validator() to check...

Laravel: Best practice for inline PHP in a blade file

So I have the following blade file: confirmEmail.blade.php @extends('layouts.master') @section('title') {{ trans('tc.signUpConfirmTitle')}} @endsection @section('body') <div class="container"> <div class="row"> <div class="col-lg-4"> &nbsp; </div> <div class="col-lg-4"> <?php echo $_GET['emailToken']; $emailToken = isset($_GET['emailToken']) ? $_GET['emailToken'] : ""; $email = isset($_GET['email']) ? $_GET['email'] : ""; //database lookup: $user = User::where('email','=',$email)->first(); //this...

Laravel 5 pagination with trailing slash redirect to 301

I'm using Laravel 5 and notice that the pagination is adding a trailing slash before the ?page=# and with that, it always redirect to a 301 page. will do a 301 redirect to This is causing my pagination using ajax to slow down because it is having 2...

Laravel5: Access public variable in another class

I have a middleware file called LanguageMiddleware.php: ... class LanguageMiddleware { //ISO language codes: public $languages = ['en','es','fr','de','pt','pl','zh','ja']; ... LanguageMiddleware.php is in laravelProj/app/Http/Middleware/ Here's my problem: I have a blade template file called master.blade.php where I'm attempting to output a list of languages @foreach (App\Http\Middleware\LanguageMiddleware\languages as $lang) <a class=\"setLang\" href=\"lang/en\">{{...

Third-party security providers like Google, Twitter etc. in ASP.Net,authentication
I have created a standard ASP.Net web project in Visual Studio 2013 and enabled authentication. A class called 'StartupAuth.cs' is created auotmatically, with following lines. When the app runs on localhost dev server it throws an exception as pasted in screen shot below the code. I need to have it...

Using middleware to call an Authentication API using ExpressJS

I'm using two Node.js + Express applications: Backend Authentication And my front-end is built in AngularJS Basically I'm trying to send a json web token with every request to the Backend, and then use a route middleware to call the Authentication API. It validates that token and add user data...

JQuery Add expiration to authentication token stored with HTML5 localStorage?

I am making a mobile game with JQuery Mobile, a multipage template (so all pages in 1 html file, which makes it usable with PhoneGap). Since it is HTML I am using JQuerys $.post function to send data to php scripts such as login.php, register.php, which add/update/delete data from the...

How to respond in Middleware Slim PHP Framework

I am creating middleware for auth into REST API. My API is created using Slim PHP Framework ,which in case provide great features to build APIs. One of this feature is Middleware. I need to check credentials in Middleware and respond with an error (HTTP code with JSON descriptions) to...

Retreiving a single colum from a pivot table - Laravel 5

I am using a pivot table genre_user to relate user to genre. table contains the following fields id user_id genre_id Following are the model definitions User.php public function genres() { return $this->belongsToMany('App\Genre'); } Genre.php public function artists() { return $this->belongsToMany('App\User'); } I am getting the results as a collection when...

Mysql - Laravel - order by and rownum position not in sync in 2 queries

So I have a list of users, who receive votes, they are ordered by votes DESC, but then I have another query that gets their current position I.E. 1st place, 2nd place, 10th, place, etc. The problem is when people have the same number of votes, the position isn't in...

Rails basic auth not working properly

I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

X509Certificate: what is the difference between getIssuerDN() and getSubjectDN() methods

I'm using X509Certificate class in java, and when I want to get the subject name I try: x509certificate.getIssuerDN().getName(); and x509certificate.getSubjectDN().getName(); both methods have the same result. So what is the difference between them ??...

Laravel 5 : on success Validation Request function

In laravel 5, we can now use the Request classes for input validation like so : public function store(StoreItemRequest $request) { $item = Item::create($request->all()); return 'success'; } When the validation fails, I can get the errors thanks to the response function in the Request class : public function response(array $errors)...

PHP custom sort on an object array Laravel-5

I need to build a custom sort on an object array but i'm not sure where to start. I've seen the functions usort() etc but I can't see how i'd implement these functions for what I require. My application is returning the below object array. I need to order it...

Handling 500 Internal Server Error from DomDocument in Laravel 5

The library I wrote for Laravel uses DomDocument. I use this library under my Controller, and its namespace is app/Services/Verify/. The library gets initialized and used when I put it some inputs into a form. When the library fails, Laravel would fail the way it would - returning the following...

Authentication with OAuth and JWT but without OpenID Connect

I’m wondering if I really need OpenID Connect to provide authentication on top of OAuth2. It seems to me if I generate JWTs (JWE) as my access token and I store user claims, roles/permissions, etc. in the access token, then the OpenID Connect's id token isn't needed. Resource servers can...

laravel 5.1 not seeing changes to Job file without VM restart

I have created a new Job in a laravel 5.1 app, running in Homestead VM. I've set it to be queued and have code in the handle method. The handle() method previous expected a param to be passed, but is no longer required and I've removed the param form the...

What is the best practice to implement update profile picture in PHP Laravel 5?

I'm trying to allow my user to update their profile photo and I'm wondering what is the best practice to implement something like that in Laravel. Here is my user profile picture. When they hover on it, they will have an option to update their photo. When the user click...