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

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 each method. I was thinking of putting it into the constructor, but as Auth::user is a static, I am making a mess of things and don't know how to do it.

Many thanks for your help !

Best How To :

You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID.

Well, this error occurred because I had '.' in place of '->'. I couldn't figure out why it was always throwing the exact same error regardless if I did $this.belongsTo('App\User'); or $this.hasMany('App\User'); or even $this.thecakeisalie('App\User'); until I sat staring at the text between my many models yet again. Then, lo...

No, you cannot enter any string. You will need to register with each provider to get the parameters that you need. See http://www.asp.net/web-api/overview/security/external-authentication-services for instructions on how to do this....

You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID. <?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesCommands; use Illuminate\Routing\Controller...

Do you mean you want to limit the number of characters in a string? This can be done in laravel by a string helper: $value = str_limit('The PHP framework for web artisans.', 7); So in your example: <p>{{ str_limit($subasta->descripcion, 20) }}</p> ...

When creating a foreign key constraint, you can also decide what should happen with the constraints. For instance, if you want to delete all articles when a category is deleted (as I guess is your question): Schema::table('articulos', function($table) { $table->foreign('categoria_id')->references('id')->on('categorias')->onDelete('cascade'); $table->foreign('creador_id')->references('id')->on('users'); }); Also see documentation. The cascade identifies to the...

Lately I favor returning events from domain methods and handling those in the application service layer. Since the application service layer is where you bring together all kinds of infrastructure further processing of the returned events, such as dispatching, can be handled in the application service layer. In this way...

As per your requirement, I blieve you have to update your relation to Polymorphic Relations. and than to access other attributes try one of them method. $user->roles()->attach(1, ['expires' => $expires]); $user->roles()->sync([1 => ['expires' => true]]); User::find(1)->roles()->save($role, ['expires' => $expires]); If you still facing some dificulties to handle that requirement let...

{{ $var or 'No Phone' }} === {{ isset($var)? $var : 'No Phone' }} Because $user->phone is defined you should use this: {{ $user->phone? $user->phone : 'No Phone' }} Or, you can go nice Laravel way and create your own directive for Blade templates and use it like this: @var($user->phone,...

It is not currently supported to use the provided Facebook and Google authentication in the same application for Advanced Mobile Access. However using the Custom Authentication option you can write your own custom authentication logic inside of your application and Node.js application. Using this method the application could handle multiple...

Until Predis' zAdd method is updated to support the changes in Redis v3.0.2, your best bet is to explore the wonderful world of RawCommand: https://github.com/nrk/predis/blob/master/src/Command/RawCommand.php It should let you construct your own commands, including the ZADD NX ... variant....

Having a look at your repository in https://github.com/Yunishawash/api-guard it looks like it doesn't have a branch called dev-fullauth. Instead there is a branch dev-bugfix. But you must not name your branch including the dev- prefix. Rename your branch at github from dev-bugfix to bugfix and then your require section would...

Are you using cygwin? You should run the commands inside the Homestead folder which is created after you do homestead init. Then you do the configuration or mapping of folders in your Homestead.yaml. it is located in you home directory. in my case in created a .homestead folder. I'm using...

As far as syncing/attaching you can use this sytanx $user->roles()->sync([1, 2, 3]); As given in Laravel Docs You can do the both checks in the condition of IF and assign in case of true, thats how your controller will look like finally. public function share(Request $request) { $userId = $request->input('user_id');...

The purpose isn't for re-direction in your routing file. Instead, with the example route you provided, Laravel will allow you to reference said route by using: $url = route('profile'); Rather then having to build the url manually in your code. So, in short: the difference is the first thing is...

I had similar problem. I modified the render function in app\Exceptions\Handler.php to public function render($request, Exception $e) { if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return response()->view('index'); } return parent::render($request, $e); } and created an index.blade.php view in resources\views folder, which was like <?php include public_path().'/views/index.html'; and it contains all the angular...

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

You want to look into polymorphic relations to solve this. You want to be able to comment on Posts and Comments. What I have done is set up a commentable trait and have the models I want to add comments to use it. This way if you ever want to...

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

Something like this may work... the idea is to add an additional select which is 0 or 1 depending on if the date is today. Then you can order by that column first, then the actual date second. public function scopeRestaurantsWithMenusToday($query, $city_uri){ return $query->where('city_uri', '=', $city_uri)->with([ 'restaurants', 'restaurants.menusToday' => function($query)...

You are trying to route something within a route definition itself. That is not how it works. There are a few ways you could do what you want to achieve. There are pros/cons to each - but they would all work. Generally the best way is to use some Auth...

That's simple php stuff. Set the attribute as static and access it with ::. class LanguageMiddleware { public static $languages = ['en','es','fr','de','pt','pl','zh','ja']; } @foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang) ... @endforeach You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and...

The relation is a hasMany and will therefor return a collection set, not one "echoable" thing: $mensajes = Messageuser::find(1)->conversaciones()->get(); $mensajes2 = Messageuser::find(4)->conversaciones()->get(); \dd($mensajes, $mensajes2); This will return two Collection objects dumped. Please also note that you can use: $mensajes = Messageuser::find(1)->conversaciones; To get the same return set. Now you want...

You can only send serializable entities to the queue. This includes Eloquent models etc. But not the PDF view instance. So you will probably need to do the following: Mail::queue('emails.factuur', array('factuur' => $factuur), function($message) { $pdf = PDF::loadView('layouts.factuur', array('factuur' => $factuur)); $message->to(Input::get('email'), Input::get('naam'))->subject('Onderwerp'); $message->attach($pdf->output()); }); ...

It looks like the middleware is being fired from the OPTIONS request. Using a more robust express library like cors will solve this problem. Alternatively, you could check for the OPTIONS request manually, then return the necessary information instead of calling next(), but unless you know exactly what you're doing,...

You cannot use halt in middleware: http://stackoverflow.com/a/10201595/2970321 Halt should only be invoked within the context of a route callback. Instead, you could manually generate a 400 response using PHP's header along with exit: header("HTTP/1.1 400 Access denied"); exit; Alternatively, you could define a new type of Exception: class AuthException extends...

1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate,...

Your scheme is not that different from the standard server-side sessions where SESSION-ID is normally nothing more than a random token and stored on the client side within a cookie, with 2 improvements: Instead of a cookie you would use Authorization header to deliver the token. This acts as a...

Before re-writing your code first thing you should analyze is why do you require Spring framework? What problem are you facing in your current architecture? Just because size of the response data stokes up shouldn't be the only reason to re-write your code. You can better design your existing code...

The usual php session_start() method is fine to use over HTTPS, and I think it is best solution for you. Let the server handle the session for you. As SilverlightFox has pointed out, it's a good idea to use http only session cookies. Before you start your session use session_set_cookie_params...

You could handle this in Laravel app/Exceptions/Hnadler.php NB: I have looked in the option of using DOMException handler which is available in PHP, however the error message you are getting in not really and exception by an I/O Warning. This what PHP native DomException looks like: /** * DOM operations...

It would be a good idea to use whereHas() on the Post model to eager load the tags and get only the Posts which have at least one of those tags. $posts = Post::whereHas('tags', function($q) use ($tags) { $q->whereIn('id', $tags); })->get(); Here, $tags would just be an array of tag...

There is a much simpler way to perform login to this website. import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36", } s = requests.session() s.headers.update(headers) # There is a dedicated login page, which is the url of the Login button on...

In your admin template you set the goto url as sessions.store which hits SessionsController::store in that method you have a debug function dd() which is throwing that string. It get's called because auth::attempt() returns false as by your own code: if($attempt) return Redirect::intended('/'); So the behavior is exactly doing what...

django.contrib.auth.login is the actual action of signing in the user. django.contrib.auth.views.login is a view that renders an HTML login form on GET request and handles POST request which internally calls django.contrib.auth.login....

Eventually you can install php DOM extension. Certain Linux distributions do not have this extension included in the minimum PHP package. It can usually be found in one of the "optional" php-* packages. On CentOS you should be able to just run yum install php-dom or yum install php-xml. That...