dimanche 17 juin 2018

Applying Laravel Policies: $this->authorizeResource('model'); is required in the controller's constructor?

I have UserPolicy:

<?php

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    public function create(User $user)
    {
        return $user->can('create_users');
    }

    public function update(User $user, User $model)
    {
        return $user->can('edit_users');
    }

    public function delete(User $user, User $model)
    {
        return $user->can('delete_users');
    }
}

and it is registered in AuthServiceProvider:

protected $policies = [
    User::class => UserPolicy::class,
];

On the other side I have UserController with create, update, destroy methods.

But UserPolicy doesn't work, it's not applied - I am still able to create, edit/update...

If I add $this->authorizeResource('user'); in the __construct() of UserController - then policies work and I cannot create/update/delete:

class UserController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource('user');
    }

But, is this the right way to do it?

If I understood Laravel's documentation well, only registering a policy in AuthServiceProvider:

   protected $policies = [
        User::class => UserPolicy::class,
   ];

... should be enough, right? Also, the authorizeResource method is NOT mentioned in the documentation.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LWCFM6
via IFTTT

Laravel Query Builder - where clause equals anything programmatically

I'm using Laravel 5.6 - Query Builder.

Is it possible to make a query builder where statement that a value equals everything programmatically?

Let's say that I have this code:

$foo = 1;

DB::table('users')
  ->select('*')
  ->where('status', '=', $foo)
  ->get();

If $foo = 1 then it's straightforward. The query will select everything with the status of 1.

Q: Is it possible to assign something to the $foo variable so the select query returns every record regardless of the status from the DB?

Of course, I can make it happen with 2 query statements like this:

$foo = 1;

if ($foo === null) {
  DB::table('users')
    ->select('*')
    ->get();
} else {
  DB::table('users')
    ->select('*')
    ->where('status', '=', $foo)
    ->get();
}

However, I'm looking for a shorter / more effective solution. Is it possible somehow - without using raw code inside the Where statement?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ypuRRg
via IFTTT

URL is not appending the port number

So I am using laravel and Browsersync for live reloading. In my webpack I have the following:

mix.js('resources/assets/js/app.js', 'public/js')
   .postCss('resources/assets/css/app.css', 'public/css', [
       tailwindcss('./tailwind.js')
   ])
    .browserSync(
    {
        proxy: 'http://twitter.test/',
        host: 'twitter.test',
        open: 'external'
    });

This makes my webpage: http://twitter.test:3000, so in my blade file I can print my urls like so:

routes = {
    'index': '',
    'store': '',
    'statuses': ''
}

Which gives me the following:

routes = {
    'index': '//twitter.test:3000/timeline',
    'store': '//twitter.test:3000/timeline',
    'statuses': '//twitter.test:3000/timeline'
}

Notce the :3000 port is in the URLS, which is what I want... Now if I go to my controller, and DD

dd(route("timeline.index"));

I get the following (which is expected; but note I am DD, not echoing)

"//twitter.test:3000/timeline"

BUT Now, if I change it to echo, like so:

echo route("timeline.index");

I get the url, without the port like so:

http://twitter.test/timeline

What is causing this, and is there a fix?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ylEoZo
via IFTTT

Laravel view not found - after clearing every cache

This is the function

public function waybills()
{
    $user = Auth::user();
    if(isset($user)){
        $uid = $user->id;
        $receives = Receive::where('receiver_code', $uid)->with('clearance')->get();
        $archives = Archive::where('receiver_code', $uid)->get();
        return view("dashboard.receive.waybills", compact('receives', 'archives'));
    }
}

and this is the structure of the directory of files

enter image description here

I tried this following artisan codes

php artisan optimize --force
php artisan config:clear
php artisan route:clear
php artisan view:clear

and the error View [dashboard.receive.waybills] not found. persists



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HUxMAM
via IFTTT

Finiding the error in my function Parse error: syntax error, unexpected '}'

Hi everyone i can't find the error in my function store():

This is the following code:

public function store(Request $request)  {

   $post= new Post();
   $post->title = $request->input('title');

    if (Auth::check()) {

    $postPhoto = Auth::user()->photo;
    $emailpost = Auth::user()->email;

} else {

    $postPhoto = public_path('/images/def.jpg');
    $emailpost = $request->input('username');
}

     $post->photo = $postPhoto;
     $post->username = $emailpost;

      $post->body = $request->input('body');
   $post->save();

   return redirect ('/ed');
}

Can anyone help me to find it?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HXQo2I
via IFTTT

Laravel 5.5 middleware does not work

I have middleware called IsAdmin, here is the code for it:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::user();

        if ($user->role === 10)
        {
            Session::flash('error', 'Трябва да сте администратор за да видите тази страница.');
            return redirect('/home');
        }

        return $next($request);
    }
}

here is registering it in the kernel:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'isadmin' => \App\Http\Middleware\IsAdmin::class,
    ];
}

and here is how I am protecting the routes in the controllers:

public function __construct()
{
    $this->middleware(['auth', 'isadmin']);
}

the auth middleware works just fine.

The isadmin middleware stopped working when I changed the permission field I use in the database, on the user model. It used to be "$user->is_admin" and I've changed it to "$user->role" now even reverting back to the old way doesn't fix the problem.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2K15EAW
via IFTTT

Default value for a photo in laravel

Hi i'm trying to make a function that allows everyone to publish whatever they want but when the visitor is not a user his post photo's default will be a photo from my directory storage that holds the meaning of anonymous or something alike:

what is the SQL command line that allows me to do so?

My post migration table is:

   Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
         $table->string('title');
          $table->string('username');
         $table->string('body');
         $table->boolean('valid')->default(0);
          $table->string('photo',150)->nullable();
            $table->timestamps();
    });

My function store() is the following:

  public function store(Request $request)
    {

   $post= new Post();
   $post->title=$request->input('title');
   $post->photo=$request->photo; //what do i change in this field?
   $post->username=$request->input('username');
      $post->body=$request->input('body');
   $post->save();
   return redirect ('/ed');
}

Any ideas would be appreciated, thank you



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2JOmAM0
via IFTTT