samedi 27 août 2016

POST controller for all routes in Laravel 5

I have callback button in header of my webpage, so user can send me message from every page. How to make route for this? Something like that:

Route::post('{*}', 'PostController@callback');



via Chebli Mohamed

Return result after the event is fired in Laravel 5.2

My original code is below

/*
   Create the Role
*/  

$result = (new RoleDb())->Create($obj);

if($result["Success"]) {

    /*
    | Get all Modules 
    */

    $Permissions = $this->Module->All($obj->RoleID);
    $list = [];

    /*
    | Prepare the list that will be assigned to Newly created role.
    */

    foreach($Permissions["Data"] as $Permission) {
        $RolePermissionOM = new RolePermissionOM();
        $RolePermissionOM->PermissionID             = $Permission->PermissionID;
        $RolePermissionOM->IsActive                 = $Permission->DefaultPermission;
        $RolePermissionOM->RoleID                   = $result["Data"];
        array_push($list, $RolePermissionOM);
    }

    /*
    | Create default permissions for above created role.
    */

    return $this->RolePermission->CreateDefaultPermissions($list, $result["Data"]);
}

Now, in my application, there are 3 more points where role is being created and instead of code duplication, I though to convert this code into event. SO whenever a role is being created, an Event is being fired to create the permission records for that role.I wrote the below code.

Event::fire(new RoleCreationEvent($result));
// `$result` contains the newly created RoleID.

Question : In my original code, I was able to get the result to check if the permissions are saved correctly or not. How will I do that in case of firing the Event ?



via Chebli Mohamed

Angular2 Can't see my custom headers attached

I am trying to attach a custom Authorization header to my get requests in my angular2 app.

Here's my code:

private headers : Headers;
  constructor (private http: Http)
  {
    this.headers = new Headers();
    //this.headers.append('Content-Type', 'application/json');
    let jwt = localStorage.getItem('id_token');
    if(jwt)
      this.headers.append('Authorization', 'Bearer ' + jwt);
  }

  private journalsUrl = Config.API_URL + 'journal';  // URL to web API

  getJournals (): Observable<Journal[]>
  {
    return this.http.get(this.journalsUrl, { headers: this.headers })
                    .map(this.extractData)
                    .catch(this.handleError);
  }

I made sure that my laravel 5 with barryvdh/laravel-cors server allowed pretty much everything related to headers:

'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => ['Authorization'],
'maxAge' => 0,
'hosts' => [],

As I debug when I look at the networks tab in google chrome looking at the headers of that particular request that fails I see: General:

Request URL:http://ift.tt/2bGZPHq
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80
Response Headers

Request Headers:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ar;q=0.6
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:api.ketabuk.dev
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

Notice that: Access-Control-Request-Headers:authorization. But notice also that the Authorization field itself is not there.

What am I doing wrong?



via Chebli Mohamed

How do you correctly implement Doctrine ACL Organisations in Laravel 5.3?

TL;DR

Does anyone have a solid example of how to implement Organisations using the Doctrine Laravel package as I feel like the docs don't say enough (or maybe i'm just after too much hand holding)


I'm trying to create and attach my user entity to an another entity that implements organisations in Doctrine Laravel but I'm completely stuck at what to do next from reading the documentation...

Currently my set up is like this:

<?php

namespace App\Entities;

use Doctrine\ORM\Mapping as ORM;
use LaravelDoctrine\ACL\Contracts\Organisation;
use LaravelDoctrine\ACL\Mappings as ACL;

/**
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="App\Repositories\ShelterRepository")
 * @ORM\Table(name="shelters")
 */
class Shelter implements Organisation
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $name = null;

    /**
     * @ORM\Column(type="string", unique=true, nullable=false)
     */
    protected $handle;


    //... Getters and setters
}

And my user entity:

<?php

namespace App\Entities;

use Doctrine\ORM\Mapping as ORM;
use LaravelDoctrine\ORM\Auth\Authenticatable;
use LaravelDoctrine\Extensions\Timestamps\Timestamps;
use Illuminate\Auth\Passwords\CanResetPassword;
use LaravelDoctrine\ACL\Mappings as ACL;
use LaravelDoctrine\ACL\Contracts\BelongsToOrganisations;

/**
 * @ORM\Entity(repositoryClass="App\Repositories\UserRepository")
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks()
 */
class User implements \Illuminate\Contracts\Auth\Authenticatable, BelongsToOrganisations
{
    use Authenticatable;
    use Timestamps;
    use CanResetPassword;

    /**
     * @ACL\BelongsToOrganisations
     * @var Shelter[]
     */
    protected $organisations;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @return Organisation[]
     */
    public function getOrganisations()
    {
        return $this->organisations;
    }

    //... Other properties and getters/setters

}

When I then run doctrine:schema:update no new columns get added nor any pivots or anything to suggest a relation between Shelter and Userand if I get the first user and try $user->belongsToOrganisation($shelter) I get:

Call to undefined method App\Entities\User::belongsToOrganisation()

I'm not really sure what to do next and the docs kinda stop at this point, am I meant to implement the rest myself? It feels like @ACL\BelongsToOrganisations on the User entity should be doing something but nothing happens so I'm not sure how I should go about adding relations etc.

Anyone with any public code where they've implemented this or any pointers would be amazing, my searches in google/youtube/github have turned up fruitless.

Thank you!



via Chebli Mohamed

config nginx(v 1.10) for laravel (v 5)with php 5.6

The config for nginx here:

user nginx;
worker_processes  4;
events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;
sendfile        on;
keepalive_timeout  65;
include /usr/local/nginx/conf/virtual/*.conf;
}

the virtual.conf in virtual file:

server {  
listen 80 default_server;

root /www/laravel/public;
index index.html index.htm index.php;

server_name laravel.rexchen.cn;

charset utf-8;

location / {
    try_files \$uri \$uri/ /index.php?\$query_string;
}

 # Note this will work with "hack" files as well as php files!
 location ~ \.(hh|php)$ {  
      fastcgi_keep_conn on;
  fastcgi_pass   127.0.0.1:9000;
  fastcgi_index  index.php;
  fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
  include        fastcgi_params;

}

# Deny .htaccess file access
location ~ /\.ht {
    deny all;
}

}

the chrome report that 500 error:enter image description here

so how fix this



via Chebli Mohamed

how to setup mysql database in laravel

i am new laravel programmer , and i have simple question about setting up database.

assume that i create all required migrations , models, and eloquent relationships, also configure mysql database in laravel, now in this point, is laravel will create all mysql tables required in server's DB according to migrations, models, and eloquent that i created before ? in other words, am i need to create tables in mysql server as scratch developer do ?

hope it's clear,

Thanks,



via Chebli Mohamed

laravel 5 query builder restrict

well i am stuck in this scenario
there is 3 tables candidate table,position table and recruitment form table. Candidate-id and position-id is a foreign key in recruitment form table when candidate apply for a position which he already applied he can't apply for that post again i tried something like this but not working . If there some error please solve it or recommend some other method to achieve this thank you.

$check = DB::table('recruitmentform')->select('positionid')->where('candidateid',$cid)->get();

    for ($i = 0; $i < count($check); $i++) {
        if ($check[$i] == $pid) {
            return redirect('/');
        }
    }



via Chebli Mohamed