samedi 30 avril 2016

How to register middlewares in OctoberCMS plugin?

Registering middlewares in Laravel is easy:

simply list the middleware class in the $middleware property of your app/Http/Kernel.php class

or

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file

But how can this be done in an OctoberCMS plugin? Is the "Routing and initialization" meant to be used in place of Kernel.php to register middlewares? If not, where can a plugin register its own middlewares?



via Chebli Mohamed

Laravel Eloquent ORM: Change model so left join is *always* performed

I have a very simple Eloquent Model:

class HelpdeskComment extends Model
{
    protected $table   = 'helpdesk_comment';
    protected $guarded = ['id', 'helpdesk_topic_id'];

    public function topic () {
        return $this->belongsTo ('\\App\\Model\\HelpdeskTopic');
    }

    public function user () {
        return $this->belongsTo ('\\App\\Model\\User');
    }
}

This all works quite well when doing stuff like

$user = $helpdeskComment->user;

However, I would like to change the model so that the User table (specifically the "username" field) is always left-joined against the HelpdeskComment table, regardless of the query function called. Is there a simple/central way to achieve this or do I have to override each function (all(), etc.)?

Thanks for any ideas & pointers.



via Chebli Mohamed

Order by descending the upadated_at column in laravel 5

$notif = DB::table('notifications')->orderBy('updated_at', 'desc')->get();

Above code is to get the values in descending order according to the default column updated_at in laravel 5. Although that will display the values ascending order. How to correct that?



via Chebli Mohamed

Laravel Error RouteCollection.php

i'm getting the error below when i migrated a project from one computer to another:

i imported the mysql table, did a migrate and when i click on the links i get a route error:

NotFoundHttpException in RouteCollection.php line 161:

My routes.php

Route::group(['middleware' =>[ 'web']], function () {
   Route::any('user/login', ['as' => 'user.login', 'uses' => 'UserController@login']);
   Route::any('user/dologin', ['as' => 'user.dologin', 'uses' => 'UserController@dologin']);
});

 Route::group(['middleware' =>[ 'web','auth']], function () {
//Route::any('/', function () { return view('user.dashboard'); });
Route::any('user/dashboard', ['as' => 'user.dashboard', 'uses' => 'UserController@dashboard']);
Route::any('user/logout', ['as' => 'user.logout' , 'uses' => 'UserController@logout']);

Route::any('sos/create', ['as' => 'sos.create', 'uses' => 'SosController@create']);
Route::any('sos/index', ['as' => 'sos.index' , 'uses' => 'SosController@index']);
Route::any('sos/store', ['as' => 'sos.store' , 'uses' => 'SosController@store']);
Route::any('sos/show/{id}', ['as' => 'sos.show' , 'uses' => 'SosController@show']);
Route::any('sos/edit/{id}', ['as' => 'sos.edit' , 'uses' => 'SosController@edit']);
Route::any('sos/update/{id}', ['as' => 'sos.update' , 'uses' => 'SosController@update']);
Route::any('sos/destroy/{id}', ['as' => 'sos.destroy' , 'uses' => 'SosController@destroy']);
Route::any('sos/submit/{id}', ['as' => 'sos.submit' , 'uses' => 'SosController@submit']);
Route::any('sos/approve/{id}', ['as' => 'sos.approve' , 'uses' => 'SosController@approve']);
Route::any('sos/reject/{id}', ['as' => 'sos.reject' , 'uses' => 'SosController@reject']);
Route::any('sos/customer-search', ['as'=>'sos.customer-search','uses'=>'SosController@search']);
Route::any('sos/customer-selected', ['as'=>'sos.customer-selected','uses'=>'SosController@customerSelected']);

Route::any('order/create', ['as' => 'order.create', 'uses' => 'OrderController@create']);
Route::any('order/index', ['as' => 'order.index' , 'uses' => 'OrderController@index']);
Route::any('order/store', ['as' => 'order.store' , 'uses' => 'OrderController@store']);
Route::any('order/show/{id}', ['as' => 'order.show' , 'uses' => 'OrderController@show']);
Route::any('order/edit/{id}', ['as' => 'order.edit' , 'uses' => 'OrderController@edit']);
Route::any('order/update/{id}', ['as' => 'order.update' , 'uses' => 'OrderController@update']);
Route::any('order/destroy/{id}', ['as' => 'order.destroy' , 'uses' => 'OrderController@destroy']);
Route::any('order/submit/{id}', ['as' => 'order.submit' , 'uses' => 'OrderController@submit']);
Route::any('order/approve/{id}', ['as' => 'order.approve' , 'uses' => 'OrderController@approve']);
Route::any('order/reject/{id}', ['as' => 'order.reject' , 'uses' => 'OrderController@reject']);
Route::any('order/customer-search', ['as'=>'order.customer-search','uses'=>'OrderController@search']);
Route::any('order/customer-selected', ['as'=>'order.customer-selected','uses'=>'OrderController@customerSelected']);
Route::any('order/ship_to_address_area', ['as'=>'order.ship_to_address_area','uses'=>'OrderController@ship_to_address_area']);
Route::any('order/dept_name_field', ['as'=>'order.dept_name_field','uses'=>'OrderController@dept_name_field']);

Route::any('equipment/create', ['as' => 'equipment.create', 'uses' => 'EquipmentController@create']);
Route::any('equipment/index', ['as' => 'equipment.index' , 'uses' => 'EquipmentController@index']);
Route::any('equipment/store', ['as' => 'equipment.store' , 'uses' => 'EquipmentController@store']);
Route::any('equipment/show/{id}', ['as' => 'equipment.show' , 'uses' => 'EquipmentController@show']);
Route::any('equipment/edit/{id}', ['as' => 'equipment.edit' , 'uses' => 'EquipmentController@edit']);
Route::any('equipment/update/{id}', ['as' => 'equipment.update' , 'uses' => 'EquipmentController@update']);
Route::any('equipment/destroy/{id}', ['as' => 'equipment.destroy' , 'uses' => 'EquipmentController@destroy']);
Route::any('equipment/loadManufacturer', ['as'=>'equipment.loadManufacturer','uses'=>'EquipmentController@loadManufacturer']);
Route::any('equipment/loadMachine', ['as'=>'equipment.loadMachine','uses'=>'EquipmentController@loadMachine']);
Route::any('equipment/loadModel', ['as'=>'equipment.loadModel','uses'=>'EquipmentController@loadModel']);
Route::any('equipment/loadImage', ['as'=>'equipment.loadImage','uses'=>'EquipmentController@loadImage']);
 });



via Chebli Mohamed

Display Omnipay Error Message in Laravel

I have a simple payment form in my Laravel 5.2 webapp. Everything works as expected except when the payment has an issue and fails. I am trying to pass the error message on a redirect back and display this message on the top of the page.

My Controller:

// Payment failed
$payment_failed_array = $response->getMessage();
//dd($payment_failed_array); // I do get the error here.
return redirect()->back()
->with('payment_failed_array', $payment_failed_array)
->withInput();

My view:

@if ( ! empty(Session::get('payment_failed_array')))
@foreach (Session::get('payment_failed_array') as $error)
<div class="col-md-9">
    <div class="tab-pane fade in active" id="alert-1">
        <div class="alert alert-danger fade in">
            <strong>Oh snap!</strong> 
        </div>
    </div>
</div>
@endforeach
@endif

I definitely thank anyone who can help me in figuring this issue out.



via Chebli Mohamed

Laravel 5: Dynamically Generate Links (Routes) to Uploades Files

I have a simple form where users can upload files. Files are uploaded to public/uploads directory.

Below the form there is a list of all the files in public/uploads directory.

So, here is my controller method:

public function store(Request $request)
{
    if ($request->hasFile('file_upload')) {
        if ($request->file('file_upload')->isValid()) {
            $request->file('file_upload')->move(public_path().'/uploads/', $request->file('file_upload')->getClientOriginalName());
        }
    }

    $list_of_files = \File::allFiles(public_path().'/uploads/');

    return view('foo', compact('list_of_files'));
}

and here is the View file that displays the list of files:

<ul>
    @foreach($list_of_files as $file)
        <li><a href="#"></a></li>
    @endforeach
</ul>

What should I put in href=" " to have links to those files (and what routes do I need to have so these links work)?



via Chebli Mohamed

Receive emails in laravel 5 from sendgrid

I'm kinda stuck with sendgrid and Laravel...

What I'm trying to make is a function in my laravel 5.1 application so users can send AND RECEIVE emails trough sendgrid. So I acctually want to integrate something like roundcube, but then in my own opplication. I already can send emails to people, but my main problem is receiving them. I already have read the full documentation page of sendgrid, but I just can't figure out how I should implementate it. I do know you need to send a post request from sendgrid to your server (app), but I don't know where in sendgrid I should place the url, and what tables I should use in my application to store the emails. Could someone please help me out with this? And give me a decent explaination of how I can implement this?

Kindest regards,

Robin



via Chebli Mohamed

form model binding in laravel 5.2

I have been reading about form model binding http://ift.tt/1SBt8ty

It's very cool to populate DB values in html form. I tried like this and this works fantastic.


    
    


But the problem is here, Cause i want to add more attributes in input like class SO i am using




If i leave blank valuecolumn then nothing populate in textbox and if i using like this




Then what is use of model binding. Please explain. Thanks



via Chebli Mohamed

Guzzle Post Request getting ERR_INVALID_CHUNKED_ENCODING when trying to access the request in controller

I'm using guzzle 6 in laravel 5 to send a post request but I'm getting ERR_INVALID_CHUNKED_ENCODING when I try to access the request() in the method that handles the post request.

Here's my code:

Routes.php

Route::get('/guzzle', [
    'as'   => 'guzzle-test',
    'uses' => 'TestController@getTest'
]);

Route::post('/guzzle', [
   'as'   => 'guzzle-post-test',
   'uses' => 'TestController@postTest'
]);

TestController.php

public function getTest()
{
    $client = new Client();

    $data = [
        'hey' => 'ho'
    ];

    $request = $client->post(route('guzzle-post-test'), [
        'content-type' => 'application/json'
    ], json_encode($data));

    return $request;
}

public function postTest()
{
    dd(request());
}

I getting to the post request handler since I've tried to diedump a string and it gets there, but if i call the request() I get that error. For what I've researched It may have something to with the content length, but after reading guzzle's docs and some stuff around the web I could find how to get and pass the content length appropriately in the request. Any help would be very appreciated!



via Chebli Mohamed

Including CSRF token in the layout

I want to include the CSRF token in the layout to make it globally accessible for my javascript code:

. . .
<body data-token="">
. . .

Is this approach a good pratice, or will it introduce any security holes / other problems?



via Chebli Mohamed

Getting null as a result

I have created two tables, First is Posts table and seconds is Comments table. I'm using sqlite database.

I'm getting null as result for comment function using hasMany method in Post Model.

Posts table migration file:

    class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('Posts');
    }
}

Comments table migration file:

 class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
{
    Schema::create('Comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('post_id')->unsigned()->index();
        $table->text('body');
        $table->timestamps();
    });
        Schema::table('Comments', function (Blueprint $table) {
            $table->foreign('post_id')->refrences('id')->on('Posts');
        });
}


/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('Comments');
}
}

Post Model:

class Post extends Model
{

    //
    public function comment(){
    return $this->hasMany(Comment::class);    
   //I have also tried: return $this->hasMany(Comment::class,'post_id','id');
    }
}

The data has been entered in both the tables and I'm getting results when I do

$post=new App\Post;
$post->get();

But when I try to get all the comments for a post using

$post->comment;

I'm getting

=>Illuminate\Database\Eloquent\Collection {#633
all:[],
}

Why am I getting null as a result?



via Chebli Mohamed

Laravel 5.2: How to customize default auth table name

I'm using Laravel 5.2, and i want to customize the default 'users' table name. i found a multiple replies for this question, so by testing all, it doesn't work: by changing /App/config/Auth.php file, by adding 'table' => 'members', and finaly renaming table name on the /database/migrations folder



via Chebli Mohamed

Undefined index when using other php variable as array key (Laravel)

my problem is that variable $this->country can not be inserted as key in array. Any one knows why ?

$array[Config::get('app.locale')][$this->country]; throws Undefined index $array[Config::get('app.locale')]['de']; throws no errors

Config::get('app.locale') var_dump string(2) "de"
$this->country            var_dump string(2) "de"




  array:1 [▼
        "de" => array:2 [▼
              "de" => "Germany"
              "us" => "USA"
        ]
  ]



via Chebli Mohamed

Laravel 5.1 .env file not recognized

I upload laravel 5.1 project in Host. and I Check the .env file with this code.

Route::get('/', function() {
    dd(env('APP_KEY'));
});

But Returned Null. How to connect .env in laravel on host? and my php version is 5.6



via Chebli Mohamed

Laravel RelationShip( join with where)

i need help on laravel 5(use Eloquent)

I have 2 tables

Model Driver drivers

  • id
  • company

Model DriverOnline drivers_online

  • id
  • name
  • driver_id

I need seatch result on (commany=1 and driver_id=driver.id) help me!



via Chebli Mohamed

Is there a way to delegate a job to another action in Laravel?

Suppose we have two models: Users, and Posts. These models have many-to-many relationship defined between them - a user can have many posts, and post can have many editors(users).

When this form is submitted to PostsController, it's store action must handle not only the new post's fields, but also it's editors, which seems wrong. Example:

enter image description here

public function store()
{
    // creating a post
    $post = Post::create(request()->get('post_fields'));

    // adding editors to the post (this should be done somewhere else)
    $editors = request()->get('editors');
    foreach($editors as $editor){
        $post->editors()->attach($editor->id);
    }

    return redirect('/');
}

As I already mentioned, this approach seems wrong and clumsy to me. Because of this I want to delegate editors handling task to PostsEditorsController, which will be a separate controller dedicated only to posts-editors relationship management. So the store will now look something like this:

public function store()
{
    // creating a post
    $post = Post::create(request()->get('post_fields'));

    $editors = request()->get('editors');
    PostsEditorsController::doSomething($post, $editors); // <-- just to show what I want to achieve

    return redirect('/');
}

How can I do this?



via Chebli Mohamed

Twig Bridge Syntax for Route

This is a valid Laravel route:



I can display this in a .twig file. How do I use it in a form_open()?

I've tried;







Just any combination really. It's very frustrating. The docs clearly say it works with route but I can't figure out the syntax.



via Chebli Mohamed

laravel file_put_contents failed to open stream: Permission denied

I have create a Module view controller structure in laravel to separate admin and user. My application works fine in localhost and after I upload the code in server I am getting this error

ErrorException in Filesystem.php line 109: file_put_contents(/fd8268e4d134db25e717cf74dd325e4ed2c672e0.php): failed to open stream: Permission denied.



via Chebli Mohamed

vendredi 29 avril 2016

Laravel 5 join table with extra condition

Hi How can i generate query like this in Laravel ELoquent

SELECT expenditure_heads.name, budget_details.budget, budget_details.id FROM expenditure_heads
 LEFT JOIN budget_details 
     ON (budget_details.expenditure_head_id = expenditure_heads.id AND budget_details.budget_id = 1)

I tried

DB::table('budget_details')
          ->leftJoin('expenditure_heads', function ($join) {
                $join->on('budget_details.expenditure_head_id', '=', 'expenditure_heads.id');
    $join->on('budget_details.budget_id','=',1);

          })

        ->select('expenditure_heads.name','budget_details.budget')

But its not working



via Chebli Mohamed

How to use variable in closure functions in php?

I am using intervention for php for image manipulations. Is it possible to apply font size and color to text through a variable like this? I have calculated $fontsize and $color above this but it says undefined variable

$img->text($string, $item['x'], $top, function($font) {
                        $font->file('assets/fonts/Roboto-Medium.ttf');
                        $font->size($fontsize);
                        $font->color($color);
                        $font->align('left');
                        $font->valign('top');
                    });



via Chebli Mohamed

How update an field by adding one itself in laravel elequent?

When user booking an offer, I want to decrease availability field in the table by one. For this,In MySQL, I can run following query

UPDATE table SET field = field - 1 WHERE id = $number

But This how can I implement in Laravel eloquent update Query method.

 $offer = Offer::find(1);
 $offer->availability = $offer->availability+1;
 $offer->save();

I know this method but I want to get equivalent to above MySQL query.



via Chebli Mohamed

Php laravel TokenMismatchException request

am try to send request by post form from but error TokenMismatchException

here is my controller code

public function postSaveedit(Request $request) {
    $var1 = $request->input('title'); //name on the form
    $var2 = $request->input('meaning'); //name on the form
    $words = User::where("title", $var1)->update(array("meaning" => $var2));

    return view('dict.watch', compact('words'));
}



via Chebli Mohamed

Why is Laravel saying "Conversion failed when converting the nvarchar value '[]' to data type int"

I'm writing a search function in Laravel, and it throws the following error: QueryException in Connection.php line 651: SQLSTATE[22018]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value '[]' to data type int. (SQL: select * from Product where pID = []).

My controller reads as follows:

public function productSearch(Request $request){
        $searchResult;
        if($request->input('category') == 'all' ){
            $searchResult = Product::where("pCategory", "like", '%')
                ->where('pName', 'like', $request->input('search'))->get();
        }else{
            $searchResult = Product::where("pCategory", "like", $request->input('category'))
                ->where('pName', 'like', $request->input('search'))->get();
        }
        //dd($searchResult);
        return view('products',['products' => $searchResult]);
    }

And the model reads as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'Product';
    protected $primaryKey = 'pID';
    //

    public function orderDetails(){
        return $this->hasMany('App\OrderDetail','ProductID','pID');
    }

}

I don't understand why it keeps doing this, especially since I am not asking it to look at the ID. What is going on here?



via Chebli Mohamed

arabic database is not working, laravel

Heelo guys , i'm trying to retrieve a stored arabic information from my sql database , the data has arrived successfully , but not arabic , it came like that : NON Arabic characters

any one can help ? here is my code



via Chebli Mohamed

How do I cache the current authenticated user? (Laravel 5)

Description

In my situation, I don't have a users table locally, but I have an api that will provide me a list of users.


getUsers()

I modify my getUsers() for my Auth::user() in app/Auth/ApiUserProvider.php

protected function getUsers()
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    curl_close($ch);

    return $response['data'];
}


Issue

Each time, I used Auth::user() in my code. It makes a call to my API .../vse/accounts It effects a lot of latency in my application.


How do I solve this ?

Should I start using cache ? If so, how do I modify what I have to do something like that ?

Should I store it in the session ?

I'm open to any suggestions right now.

Any hints / suggestions on this will be much appreciated !



via Chebli Mohamed

Many to Many relationship works one way

I have a User and a Quiz models. I have many-to-many relationship defined between them in the following way:

User model

public function subscriptions()
{
    return $this->belongsToMany(Quiz::class, 'subs_users', 'quiz_id', 'user_id')->withTimestamps()->withPivot('accepted');
}

Quiz model

public function subscribers()
{
    return $this->belongsToMany(User::class);
}

Pivot table

Schema::create('subs_users', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->integer('quiz_id')->unsigned();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('quiz_id')->references('id')->on('quizzes')->onDelete('cascade');

    $table->primary(['user_id', 'quiz_id']);

    $table->boolean('accepted')->index();

    $table->timestamps();
});

When I call $quiz->subscribers, it returns a collection of users as expected. However, $user->subscriptions always returns an empty array. Why is that?



via Chebli Mohamed

How to get count for all products for all categories (i.e all records on many-to-many table) with laravel 5.2

This what i want to do is to take the count of entries from many-to-many table. I can do it with a simple query, but I can use the ORM of Laravel 5.2. These are my models:

Category model

class Category extends BaseModel {
    protected $table = 'categories';

    public function products() {
        return $this->belongsToMany('App\Models\Product', 'product_category');
    }

Product model

class Product extends BaseModel {
    protected $table = 'products';

    public function categories() {
        return $this->belongsToMany('App\Models\Category', 'product_category')->withTimestamps();
    }

I want to add a method in the Category model or using the Laravel ORM to take the number of all products for all categories i.e the number of all records from the product_category table. How can I do it ?



via Chebli Mohamed

Some questions on laravel 5

I have some sort of beginner intermediate question about the laravel 5 framework.

  • When to use facade and when to use DI. To someone who is complete new to Laravel these two concept are a little hard to grasp. Here is an example.
<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class UserController extends Controller {
    public function store(Request $request)
    {
        $name = $request->input('name');
    }
}

vs using this

<?php namespace App\Http\Controllers;

use Request; // Facade of Illuminate\Http\Request
use Illuminate\Routing\Controller;

class UserController extends Controller {
    public function store()
    {
        $name = Request::input('name');
    }
}
  • If we wanted to create our own classes to use where can we put our own classes in the laravel default folder structure?

  • Is Illuminate being assembled by composer? How do we know which classes to use from the illuminate namespace?

  • If the project was hosted on a different server other than the default php server that comes with laravel, do we need to change the .htaccess?

  • -


via Chebli Mohamed

foreach loop is repeating form fields laravel

Tomorrow i am going to present my code in sprint. All was working fine till few hours ago. i have a modal which popus when user clicks on Edit. It was giving the values according to id

<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
@foreach($Community as $editCommunity)
<h4 class="modal-title">Edit: {!! $editCommunity->community_name !!}</h4>
</div>
<div class="modal-body">
<form class="form-group" action="/update/" method="post" id="editCommunityForm">
<input type="hidden" name="_token" value="">
<input type="text" name="community_name" class="form-control" value="">
</form>
@endforeach
<button class="btn btn-custom dropdown-toggle waves-effect waves-light" type="submit" form="editCommunityForm">Update Community</button><br /><br />
</div>
<div class="modal-footer">

</div>
</div>

</div>
</div>

I am very upset and confused and don't know what to do. Any help would highly be appreciated

See this image to get proper understanding



via Chebli Mohamed

Laravel Homestead with BrowserSync

I'm trying to use browsersync with Laravel. I followed this tutorial from laracasts but my browsersync isn't syncing.

Here's my gulpfile:

var elixir = require('laravel-elixir');
elixir(function(mix) {
    mix.sass('app.scss');
    mix.browserSync();
});

My app is homestead.app. So, after starting gulp watch, I go to homestead.app:3000 and see my app without BrowserSync.

I go to homestead.app:3001 and I can access BrowserSync dashboard, which shows this:

Local http://localhost:3000

External http://10.0.2.15:3000

Proxying: http://homestead.app

Current Connections Connected browsers will be listed here.

Local and external links not responding.

No matter what I did, I couldn't see any connection in Current Connections tab.

What I tried:

tried running gulp watch from my local environment instead of homestead.

This time both Local and external links were pointing to my app, but no syncing.

I'm using windows 8.1

Any help would be appreciated.



via Chebli Mohamed

Laravel 5.2 Flash Issue with Redirect & Middleware

I currently have two set of codes , one works well with Session/Flash one doesn't.

Basically a Signup/Login form has got no issue displaying Flash , but they are not under any middleware.

Route::get('signup', ['uses' => 'HomeController@signup']);
Route::post('signup', ['uses' => 'HomeController@postSignup']);
Route::get('login', ['uses' => 'HomeController@login']);
Route::post('login', ['uses' => 'HomeController@postLogin']);

Things starts to get tricky when i started applying web & auth middleware to a group of code.

Route::group(['middleware' => ['web','auth']], function () {
Route::post('claimForm', ['uses' => 'HomeController@claimForm']);
}

The problem with this claim form is , the flash will be dropped if I do a redirect.

   $request->session()->flash('pass', 'Claim Submitted!');
    return redirect('/dashboard');

BUT if i do a return VIEW instead of redirect, the flash works perfectly fine.

I tried to remove web from middleware , now the flash will stay at a few pages, random timing and frequency each time I submit.

  • I tried to remove the whole middleware, things started to work normally. The flash will only happen once. Without the Web& Auth middleware.

I cant afford to not have middleware , so please advice. I have 3 Route::groups.With middleware inplace, I tried to re-flash on the GET which the POST is redirecting to but it also wont work.



via Chebli Mohamed

laravel config.database.php changing 'strict' mode to true blocks "mysqli_connect" to fail connecting remote database

I am using Laravel for a bit of time and at one point in order to solve "created_at column does not have default value" error, I modified the config/database.php file by setting 'strict'=true.

That solved my problem, but after setting it true I am not able to connect to remote database using "mysqli_connect" for which I was able to connect before this change. I set that 'strict' mode back to false but it still fails to connect the external database using "mysqli_connect" function.

I tried to clear the cashes and look into .env file but nothing helps. I am very stuck with this, any help would be very appreciated.



via Chebli Mohamed

laravel: get name of active log at runtime

I need to know the name of the current log in an app laravel 5.

Try search for this on Iluminate\Log\Writer.

Only see $path var on call to some functions, but i don't understand how to get this value.

Basically I needs to compress file and send if app get some exceptions. For this I need to know the name of active log.

My app conf log for daily rotation, and see name of logs such laravel-2016-04-29.log

I know the name using php, but I imagine it is possible to know using the Log class itself



via Chebli Mohamed

Laravel 5 routes and mod_rewrite

I have a simple routes.php file, that looks like this:

Route::group(['middleware' => 'cors', 'prefix' => 'api'], function () {
  Route::post('users', 'Api\UsersController@save');
  Route::get('users/{userId}/leagues/', 'Api\UsersController@saveFavoriteLeague');
});

Once I put my application to server, I couldn't get to any of the routes executed. I was getting 404 exception.

I tried to make an obvious error in routes.php file, by putting 123 at the top of the file. Then I hit http://ift.tt/1Ta85KB, and I was expecting error page, that there is a syntax error, but that didn't happen (still getting 404). However, when adding something like this:

Route::get('/', function() {
   return 'Hello';
});

and hitting home route mydomain.com, I was able to see at first syntax error, and then after fixing it, Hello.

I spent hours until I discovered that mod_rewrite, wasn't enabled on the remote server.

Can someone put more light on this? Why my requests didn't reach routes.php (not even to show that there is an syntax error), but instead 404 page was returned. Why mod_rewrite made it to work? How could / reached the route.php, but /users e.g. didn't?

Thanks!



via Chebli Mohamed

Why am I getting a MethodNotAllowedHttpException on a resourceful route?

I keep getting a MethodNotAllowedHttpException error on a resourceful route that I have set up. The patch/put requests exist when I run php artisan route:list, my form refers to jobs.update and passes on the id. I use this same process for all of the application's other modules without such an issue. Any ideas where the exception might be coming from?

My routes file:

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

//Homepage...
Route::get('/', function () { return view('homepage'); });

// Resourceful modules...
Route::resource('conferences', 'ConferencesController');
Route::resource('pages', 'PagesController');
Route::resource('jobs', 'JobsController');
Route::resource('admin/menu', 'MenuItemsController');



// Actions...
Route::put('admin/menu/{id}/promote', [
    'as' => 'admin.menu.promote', 'uses' => 'MenuItemsController@promote'
]);
Route::put('admin/menu/{id}/demote', [
    'as' => 'admin.menu.promote', 'uses' => 'MenuItemsController@demote'
]);
Route::get('{parent}/{slug}', 'PagesController@show');
Route::get('{slug}', 'PagesController@showSlug');

My update method:

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $job = $this->job->find($id);
        $job->update($request->all());
        return redirect('jobs.index');
    }

My form:

        <form action="" method="POST" class="col s12" enctype="multipart/form-data">
        {!! csrf_field() !!}
        <div class="row">
            <div class="input-field col s12 m6">
                <input type="text" name="position" id="position" class="validate" placeholder="Position" value="">
                <label for="position" class="col-sm-3 control-label">Position</label>
            </div>
            <div class="input-field col s12 m6">
                <select name="type" id="type">
                    @if($job->type == "full")
                        <option value="" disabled selected>Type</option>
                        <option value="full" selected>Full-time</option>
                        <option value="part">Part-time</option>
                        <option value="other">Other</option>
                    @elseif($job->type == "part")
                        <option value="" disabled selected>Type</option>
                        <option value="full">Full-time</option>
                        <option value="part" selected>Part-time</option>
                        <option value="other">Other</option>
                    @elseif($job->type == "other")
                        <option value="" disabled>Type</option>
                        <option value="full">Full-time</option>
                        <option value="part">Part-time</option>
                        <option value="other" selected>Other</option>
                    @else
                        <option value="" disabled selected>Type</option>
                        <option value="full">Full-time</option>
                        <option value="part">Part-time</option>
                        <option value="other">Other</option>
                    @endif
                </select>
                <label>Type</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m6">
                <input type="text" name="reports_to" id="reports_to" class="validate" placeholder="Reports to" value="">
                <label for="reports-to" class="col-sm-3 control-label">Reports to</label>
            </div>
            <div class="input-field col s12 m6">
                <input type="text" name="office_department" id="office_department" class="validate" placeholder="Reports in office" value="">
                <label for="office_department" class="col-sm-3 control-label">Reports in office</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m6">
                <input type="date" class="datepicker" name="start_date" id="start_date" class="validate" value="">
                <label for="start-date" class="col-sm-3 control-label">Start date</label>
            </div>
            <div class="input-field col s12 m6">
                <input type="date" class="datepicker" name="application_due_date" id="application_due_date" class="validate" value="">
                <label for="application_due_date" class="col-sm-3 control-label">Application Due Date</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m6">
                <input type="text" name="city" id="city" class="validate" placeholder="City" value="">
                <label for="city" class="col-sm-3 control-label">City</label>
            </div>
            <div class="input-field col s12 m6">
                <input type="text" name="state" id="state" class="validate" placeholder="State" value="">
                <label for="state" class="col-sm-3 control-label">State</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m6">
                <input type="text" name="institution" id="institution" class="validate" placeholder="Institution" value="">
                <label for="institution" class="col-sm-3 control-label">Institution</label>
            </div>
            <div class="input-field col s12 m6">
                <input type="text" name="salary_range" id="salary_range" class="validate" placeholder="Salary Range" value="">
                <label for="institution" class="col-sm-3 control-label">Salary Range</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m12">
                <p class="col-sm-3 control-label">Job Description</p>
                <textarea name="job_description" id="job_description" class="mce validate"></textarea>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m12">
                <p class="col-sm-3 control-label">Job Duties</p>
                <textarea name="job_duties" id="job_duties" class="mce validate" ></textarea>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m12">
                <p class="col-sm-3 control-label">Qualifications</p>
                <textarea name="qualifications" id="qualifications" class="mce validate" ></textarea>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m12">
                <p class="col-sm-3 control-label">Benefits</p>
                <textarea name="benefits" id="benefits" class="mce validate" ></textarea>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s12 m12">
                <p class="col-sm-3 control-label">Application Procedure</p>
                <textarea name="application_procedure" id="application_procedure" class="mce validate" ></textarea>
            </div>
        </div>
        <div class="row">
            <div class="input-field">
                <button class="btn waves-effect waves-light col s12 m3" type="submit" name="action">Submit
                    <i class="material-icons right">send</i>
                </button>
            </div>
        </div>
    </form>



via Chebli Mohamed

Displaying loading animation while waiting

I have a button like so

{!! link_to_route('jobs.createJob', 'Create Job', $job->id, array('class' => 'btn btn-info')) !!}

So this route calls a function which does something like this

public function createJob(Job $job) {
    $createJob = Helper::createNewJob($job);
    $createJobXML = new \SimpleXMLElement($createJob);
    if($createJobXML->Status == 'OK') {
        $job->jobNumber = $createJobXML->Job->ID;
        if($job->update()) {
            $assignStaff = Helper::assignStaffToJob($job);
            $assignStaffXML = new \SimpleXMLElement($assignStaff);
            if($assignStaffXML->Status == 'OK'){
                $createQuoteForJob = Helper::createQuoteForJob($job);
                $createQuoteForJobXML = new \SimpleXMLElement($createQuoteForJob);
                if($createQuoteForJobXML->Status == 'OK'){
                    $job->quoteId = $createQuoteForJobXML->ID;
                    if($job->update()) {
                        return View::make('jobs.show', compact('job'));
                    }
                }
            }
        }
    }
    return View::make('campaigns.show', compact('job'));
}

So there is quite a lot going on which involves hitting several API methods to insert data into a system. This process can sometimes take a few seconds, and I do not want them being able to click the submit button again, so I want to show them a loading screen while this happens.

If I was making this request via ajax I could simple use ajaxStart and ajaxComplete. However, I am not using ajax, so is there another way I could do this within Laravel 5?

Thanks



via Chebli Mohamed

Laravel 5.2 - Multiple relations

This is my first Laravel 5 project.

DB tables Image

I have a 'members'-function in my Group controller with the following code:

public function members() {
    return $this->belongsToMany('App\User', 'group_members')->withPivot('status', 'right_id')->withTimestamps();
}

When I call this function it will return the members of a specific function.

Now I want to call a function called 'rights' or something like that, which will return the right_id and the type of the 'rights' table in a single line of code.

Now when I want the right_id of a member I use this line:

$group->members->where('id', Auth::user()->id)->first()->pivot->right_id

But then I dont have the 'rights'-type because the right_id is in the 'group_members'-table.

I want it to work something like this:

$group->members->where('id', Auth::user()->id)->first()->rights

I hope that this is enough information to give me some advice, or even a solution for this problem.

I know this could also be done by making a custom query, but I like the way Laravel works.



via Chebli Mohamed

How can I optimize my Model/DB Query relationship?

I have a Recipe Eloquent model. With so many relationships it was too inefficient (read "slow") to use for a RESTful API response. I get much better performance using the DB query shown below, and then the cache on top of that takes what took up to 30 seconds before and delivers it in less than a second. I understand that maybe a better method would be to have a single flat table for API request such as the one shown below, but that isn't immediately possible.

So...

  1. I'd like to have all of my recipe methods continue to live in one place, whether it be an Eloquent model or elsewhere. Should the query below be a method within my model?
  2. Can my DB query be done in Eloquent without sacrificing performance?
  3. If the query below cannot live within my model, is there any literature on where a DB query should live so that it is easier to manage the object and keep it scalable?

Details:

$recipes = Cache::remember("query-recipe-all-{$this->getLocation()}-{$this->getItemsPerPage()}-{$request->input("start")}-{$request->input("end")}", $cacheExpireAfterMinute, function () {
    return DB::connection('remoteRecipes')->table('Recipe')
       ->join('HowServed', 'Recipe.serveid', '=', 'HowServed.serveid')
       ->join('Colors as Color', 'Recipe.colorid', '=', 'Color.colorid')
       ->join('Glass as GlassType', 'Recipe.glassid', '=', 'GlassType.glassid')
       ->join('BeverageType', 'Recipe.bevtypeid', '=', 'BeverageType.bevtypeid')
       ->join('UOM as UnitOfMeasure', 'Recipe.servingsizeuomid', '=', 'UnitOfMeasure.uomid')
       ->join('Equipment', 'Recipe.equipmentid', '=', 'Equipment.equipmentid', 'full outer')
       ->join('Methods as Method', 'Recipe.methodid', '=', 'Method.methodid')
       ->join('RecipeImages as Images', 'Recipe.recGUID', '=', 'Images.RecipeID')
       ->select(
          'Recipe.recGUID as masterRecipeId',
          'Recipe.MoninDotCom_SKU as alt_id',
          'Recipe.credat as date_created',
          'Recipe.updat as date_updated',
          'Recipe.locationid as locationId',
          'Recipe.location as locationTextId',
          'Recipe.publishedname as titlePreferred',
          'Recipe.description as title',
          'HowServed.serveid as servedHowId',
          'HowServed.served as servedHowLabel',
          'HowServed.location as servedHowLocation',
          'Color.colorid as colorId',
          'Color.color as colorLabel',
          'Color.location as colorLocation',
          'GlassType.glassid as glassTypeId',
          'GlassType.glass as glassTypeLabel',
          'GlassType.location as glassTypeLocation',
          'Recipe.LevelOfDifficulty as levelOfDifficultyId',
          'Recipe.alcohol as hasAlcohol',
          'BeverageType.bevtypeid as beverageTypeId',
          'BeverageType.bevtype as beverageTypeLabel',
          'BeverageType.location as beverageTypeLocation',
          'Recipe.servingsize as servingSize',
          'UnitOfMeasure.uomid as uniteOfMeasureId',
          'UnitOfMeasure.uom as uniteOfMeasureLabel',
          'UnitOfMeasure.location as uniteOfMeasureLocation',
          'Equipment.equipmentid as equipmentId',
          'Equipment.equipment as equipmentLabel',
          'Equipment.location as equipmentLocation',
          'Recipe.Rating as recipeTagRatingInternal',
          'Recipe.isCoffee as recipeTagIsCoffee',
          'Recipe.isFood as recipeTagIsCulinary',
          'Recipe.isHome as recipeTagIsForHome',
          'Recipe.isBar as recipeTagIsForBar',
          'Method.methodid as methodId',
          'Method.methodName as methodLabel',
          'Method.location as methodLocation',
          'Recipe.Instructions as instructions',
          'Recipe.recGUID as IngredientsLookupId',
          'Recipe.recGUID as GetProductsUsedInIngredients',
          'Recipe.recGUID as Garnish.LookupId',
          'Recipe.recGUID as Seasons.LookupId',
          'Images.*'
       )
       ->where('Recipe.location', '=', $this->getLocation())
       ->where('Recipe.web', '=', 1)
       ->where('Images.apptype', '=', "monin.com US")
       ->whereBetween('Recipe.updat', [$this->getListFromDate(), $this->getListToDate()])
       ->orderBy('Recipe.updat', 'DESC')
       ->paginate($this->getItemsPerPage());
  });



via Chebli Mohamed

Stripe update an existing customers card

having an issue with stripe at the moment. I believe I'm missing something incredibly simple here.

So on a project of mine customers can buy products and all the payments are handled with stripe. When a customer first uses stripe to make a payment i create a customer within stripe and store their id in my db. If they already exist i retrieve the customer and update the card (or try to)

This is my code

        // check if we already have their stripe info
        if ($customer->stripe_id != NULL) {
            $stripe_customer = \Stripe\Customer::retrieve($customer->stripe_id);
            $stripe_customer->card = $input['stripe_token'];
        } else {
            $stripe_customer = \Stripe\Customer::create([
                'card' => $input['stripe_token'],
                'email' => $customer->email,
                'description' => 'Customer #' . $customer->id,
            ]);
            $this->customersRepo->update($customer->id, ['stripe_id' => $stripe_customer->id]);
        }

        // charge accordingly
        $charge = \Stripe\Charge::create([
            'customer' => $stripe_customer->id,
            'amount' => $order->order_total * 100,
            'description' => 'Payment for order #' . $order->order_ref . ' from ' . route('home'),
            'currency' => 'gbp',
            'metadata' => [
                'order_ref' => '#' . $order->order_ref,
                'customer_id' => $customer->id,
                'customer_name' => $customer->user->present()->fullName,
                'customer_email' => $customer->user->email
            ]
        ]);

Which all works perfectly fine but when I try to pay with a different card it uses the card previously supplied so the customer doesn't seem to be updating?

For example, I am using the test card number 4242424242424242 to simulate a normal payment which is fine and works correctly.

But when I try to use 4000000000000002 to simulate a card error on the same customer it still goes through as paid, which leads me to believe the previous card is being used.

Any way around this or am I missing something?

Thanks,



via Chebli Mohamed

new and static used at once in laravel 5

I encounter with one strange line of code in the larvel 5.0

echo (new static)->getMorphClass();

This echo the namespace of the model. Now didn't understand how come new and static are used at once.

PHP version is 5.6.3



via Chebli Mohamed

Laravel listener subscribe to all events

I know that I can put a list of all the events but it's just stupid.

public function subscribe($events)
{
    $events->listen(
        'App\Events\UserLoggedIn',
        'App\Listeners\UserEventListener@onUserLogin'
    );

    $events->listen(
        'App\Events\UserLoggedOut',
        'App\Listeners\UserEventListener@onUserLogout'
    );
}

I'd like to use some sort of wildcart. Is it possible?



via Chebli Mohamed

Laravel 5 route to controller outside the namespace or route to another controller

I want to route to a adminController which is located under Administration Module : App\Modules\Administration\Http\Controller to perform addUser action.

To call the AdminController, i am using the route.php located under App\Modules\User. Below is my route.php in user module.

Route::group(array('namespace'=>'App\Modules\Administration\Http\Controllers'), function(){

        Route::post('/addUser', [
            'uses' => 'adminController@addUser',
            'as' => 'addUser'
        ]);

    });

But i am getting error saying route does not exist. can you help me out?.



via Chebli Mohamed

Month specific query Mongodb and laravel

I'm working with laravel molequent for mongoDb and I want to write a query which compares the current month between two dates. Suppose I have start_date and end_date, if I write query in mysql it will be:

select * from table where month(curdate()) between month(start_date) and month(end_date) ;

Now I have to write this query in mongoDb with laravel query builder.



via Chebli Mohamed

Laravel 5.0 can't parse array to view

Can't parse array to view.

Here is the array

 Array (
    [positions] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [company_id] => 1
                    [title] => Software Developer
                )

            [1] => Array
                (
                    [id] => 2
                    [company_id] => 2
                    [title] => Accountant
                )

            [2] => Array
                (
                    [id] => 3
                    [company_id] => 3
                    [title] => Insurance salesman
                )
        )
)

this is the controller

$data = array(
    'positions' => $newarray['data']
);
return view('mypage', $data);

and this is the view where i try to echo the title

@foreach($positions as $position)
<br>
@endforeach

i get this error in the view "Trying to get property of non-object"



via Chebli Mohamed

ReflectionException - Class does not exist after creating http middleware on Laravel 5

I just want to add HTTP middleware for filtering user role but I get this error:

ReflectionException in Container.php line 779: Class create:comptable does not exist

in Container.php line 779
at ReflectionClass->__construct('create:comptable') in Container.php line 779
at Container->build('create:comptable', array()) in Container.php line 659
at Container->make('create:comptable', array()) in Application.php line 644
at Application->make('create:comptable') in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Router.php line 703
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 670
at Router->dispatchToRoute(object(Request)) in Router.php line 628
at Router->dispatch(object(Request)) in Kernel.php line 214
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 43
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 115
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53
at require_once('C:\wamp\www\Medecin2016\public\index.php') in server.php line 21

And this is what I do: Create middlerware "create":

<?php namespace App\Http\Middleware;

use Closure;

class CreateInfos {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$comptable)
    {
        $User = $request->user();
        return ($User->hasRole($comptable)) ? $next($request) : response(view('errors.503'),401);
    }

}

Set a short name by editing Kernel.php file:

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'create' => 'App\Http\Middleware\CreateInfos',
        'update' => 'App\Http\Middleware\UpdateInfos',
        'delete' => 'App\Http\Middleware\DeleteInfos',
    ];

}

And adding the middleware to Routes file:

Route::get('profile/diplomes'           ,['middleware'=>'create:comptable','uses'=>'ProfileFormsController@getFormDiplomes']);
Route::post('profile/diplomes'          ,['middleware'=>'create:comptable','uses'=>'ProfileFormsController@postDiplomes']);
Route::post('profile/update/diplomes'   ,['middleware'=>'create:comptable','uses'=>'ProfileFormsController@updateDiplomes']);
Route::post('profile/delete/diplomes'   ,['middleware'=>'create:comptable','uses'=>'ProfileFormsController@deleteDiplomes']);



via Chebli Mohamed

Laravel and Brew installation with PHP and PDO

I have just moved from linux to mac and am having some issues installing PHP with the right drivers for Laravel.

I ran brew install homebrew/php/php56-mysqlnd_ms

but now I keep getting this error

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/local/opt/php56-mcrypt/mcrypt.so' - dlopen(/usr/local/opt/php56-mcrypt/mcrypt.so, 9): image not found in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library '/usr/local/opt/php56-mcrypt/mcrypt.so' - dlopen(/usr/local/opt/php56-mcrypt/mcrypt.so, 9): image not found in Unknown on line 0
phpinfo()

PHP Version => 5.6.21

Does anybody know how to fix this error? I am at a loss



via Chebli Mohamed

Google/YouTube API Refresh token required

So basically. I know that you request first auth and only get refresh token once per app. And this means, you need to use that refresh token, to grab another access token. Which my application is doing perfectly, although.. once it refreshes the token, I'm getting errors saying my application needs another refresh_token to continue, although I just refreshed using the token and have obtained an access token.

So i don't understand where I go from here? the only thing I know to do is throw the user back into sign in screen once again. And that's just damn annoying, since we want them to link their accounts once and allow access



via Chebli Mohamed

Join statment in controller not working Laravel 5.0

Works perfectly in routes but does not work in controller. What might be wrong?

    public function index(){

    $positions = DB::table('position')
    ->join('company', 'position.company_id', '=', 'company.id')
    ->select('position.*', 'company.name')
    ->get();

    //Just to check if its working
    print_r($positions);
}



via Chebli Mohamed

How to create conditional query with IF(expression, value_if_true,value_if_false) in laravel?

How to create query like this ?

SELECT id,name,if(id > 17,'yes','no')as present FROM `ref`;



via Chebli Mohamed

How to refresh values in laravel models where enums are replaced with values?

So I came across a weird issue while writing tests in laravel using factories. So this is a test I wrote:

/**
 @test
 */
public function document_belongs_to_a_patent()
{
    $patent = factory(Patent::class)->create();

    $document = factory(Document::class)->create([
        'documentable_id' => $patent->id,
        'documentable_type' => 'patent'
    ]);

    $this->assertArraySubset($patent->toArray(), $document->documentable->toArray());
}

So this should work, right because both should return the same thing and patent array should be equal or a subset of documentable array. But it was failing when I realised that there is an enum field in Patent model to which I am passing the value 1 but it was converted to the enum equivalent value in the database and when I tried document->documentable->toArray() it came back with the enum value rather than 1 which got me thinking how can make the model factory return the actual enum value and not the index number.

Top of the head I just fetched the patent just after creating it via the factory like so:

$patent = Patent::find($patent->id);

And it works well but it seems inconsistent. Is there a way to refresh models. I know we can refresh relationships of models but is there a way to do for the models themselves?



via Chebli Mohamed

jeudi 28 avril 2016

How to optimise hadle of big data on laravel?

Everyone! I have some problem. My task is: "To take transactions table, grouped row by transaction date and calculate statuses. This manipulations will be formed statistics, wich will be rendered on the page".

This is my method of this statistics generation

public static function getStatistics(Website $website = null)
    {
        if($website == null) return [];

        $query = \DB::table('transactions')->where("website_id", $website->id)->orderBy("dt", "desc")->get();

        $transitions = collect(static::convertDate($query))->groupBy("dt");
        $statistics = collect();

        dd($transitions);

        foreach ($transitions as $date => $trans) {
            $subscriptions = $trans->where("status", 'subscribe')->count();
            $unsubscriptions = $trans->where("status", 'unsubscribe')->count();
            $prolongations = $trans->where("status", 'rebilling')->count();
            $redirections = $trans->where("status", 'redirect_to_lp')->count();
            $conversion = $redirections == 0 ? 0 : ((float) ($subscriptions / $redirections));
            $earnings = $trans->sum("pay");

            $statistics->push((object)[
                "date" => $date,
                "subscriptions" => $subscriptions,
                'unsubscriptions' => $unsubscriptions,
                'prolongations' => $prolongations,
                'redirections' => $redirections,
                'conversion' => round($conversion, 2),
                'earnings' => $earnings,
            ]);

        }

        return $statistics;
    }

if count of transaction rows below 100,000 - it's all wright. But, if count is above 150-200k - nginx throw 502 bad gateway. What can you advise to me? I'm dont' have any expierince in bigdata handling. May be, my impiments has fundamental error?

Thanks.



via Chebli Mohamed

How to setup a laravel queue job which runs continuously for checking pending records in database

I'm new to Laravel queues my requirement is to fetch chunks of records from a million records table and queue them to process data and store back to some other database.

1) How to setup a queue which fetches chunks of data from database and iterate through records to add to queue.

2) Initiate multiple works to process queued jobs to speedup the process.

3) Supervisor config to run the queue for ever.

Thanks.



via Chebli Mohamed

How can I more organize this Laravel DB query?

I'm new to Laravel and I'm implementing product categories logic using Nested Set Model.

http://ift.tt/12pRuNw

The following query is to get immediate subordinates of a node and it's really hard for me to figure out how to organize this raw SQL query into simple and readable Laravel expressions using Laravel query builder. Any suggestion?

DB::select('SELECT node.name, 
(COUNT(parent.name) - (sub_tree.depth + 1)) AS depth 
FROM categories AS node, categories AS parent, 
categories AS sub_parent, 
( SELECT node.name, (COUNT(parent.name) - 1) AS depth 
    FROM categories AS node, categories AS parent 
    WHERE node.lft BETWEEN parent.lft AND parent.rgt 
    AND node.id = :id GROUP BY node.name ORDER BY node.lft) AS sub_tree 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
    AND sub_parent.name = sub_tree.name 
GROUP BY node.name 
HAVING depth = 1 
ORDER BY node.lft', ['id'=>$this->attributes['id']]);



via Chebli Mohamed

Why my input validation is not working (laravel 5)?

I am using Laravel 5 and I want to use input validation for my form. But my validation is not working. Do you know why?
Here is the view:

<div class="form-group"><br>

        <label for="jenis_surat" class="control-label col-sm-2">Jenis Surat</label>
        <div class="col-sm-7">

          <script type="text/javascript">
        @if($errors->any())
            <div class="alert alert-danger">
                @foreach($errors->all() as $error)
                    <p></p>
                @endforeach
            </div>
        @endif
      </script>

            <input class="form-control" type="text" name="jenis_surat" id="jenis_surat">
        </div>  
        <div class="col-md-1">
          <input class="form-control" type="hidden" name="_token" value="">
          <a class="btn btn-success" data-toggle="modal" data-target="#konfirmasi_submit_jenis_surat">Submit</a>   
        </div>
    </div>

and this is the controller:

public function tambahjenissurat(Request $request)
{
    //input validation
    $this->validate($request, [
        'jenis_surat' => 'required'
    ]);

    $jenis_surat = $request['jenis_surat'];

    $jenissurat = new JenisSurat();
    $jenissurat->jenis_surat = $jenis_surat;

    $jenissurat->save();

    return redirect()->route('jenissurat');
}



via Chebli Mohamed

Does Laravel5 transaction work or not if I create method instead of using eloquent or query builder in my controller method

I'm so concern about my operation to used Mysql statement like update, delete, insert and within Laravel Eloquent or Query builder because I've create more Mysql statement with more conditional inside of my method in Controller so if one of that conditional or something occurs or meet any problem during I'm processing my method in controller Method I will lost my information or data my data which I want to insert or update to my database.

As below function I used setNotification() which I create in Notification Model and I have method inside that Model which I want to call it to post_data is a method in Controller so if I do so does DB::beginTransaction() will work or not because I prefer to keep all Mysql statement inside all method in Model.

now I currently using Laravel Transaction with Try catch

public function post_data() {

  if (Request::ajax() && $this->CheckPermId_from_session(90)) {

     $res = null;
     $data = Request::except(['_token']);
     $rules = [//rules varray];
     $data = [//Input data];
     $data['tranx_time'] = date("y-m-d H:m:s", time());
     $val = Validator::make($data, $rules);
     if ($val->fails()) {

           $res = ['res' => false, 'form' => false, 'data', $data];
     } else {

           DB::beginTransaction();
           try {

          //$update = Teller::where('id', '=', Request::input('teller_till_id'))->update(array('balance' => Request::input('tell_balance')));
           $updateTeller = Teller::where('id', '=', Request::input('chief_till_id'))->update(array('balance' => Request::input('last_chief_balance')));
          $insertId = DB::table('till_transaction')->insertGetId($data);
    if ($insertId && $updateTeller) {
          $this->notification->setNotification([$data['to_account'], json_encode($this->group_code), $insertId, Request::input('chief_till_id'), $data['type'], date("Y-m-d H:m:s", time()), $data['type']]);
          $res = ['res' => true, 'data', $data];
    } else {
               $res = ['res' => false, 'data', $data];
           }
           DB::commit();
       } catch (Exception $e) {
           DB::rollBack();
           throw $e;
      }
    }
    return $res;
   }
  }



via Chebli Mohamed

Change S3 Endpoint in Laravel

I used the filesystems.php file to configure my S3. When I try to put content in the bucket I receive this error:

Encountered a permanent redirect while requesting http://ift.tt/247QTkd... Are you sure you are using the correct region for this bucket?

I then try to acces the url and I get this message:

The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

On the same page I get:

<Endpoint>s3.amazonaws.com</Endpoint>

Then how could I remove the region from the URL Laravel generates?



via Chebli Mohamed

Laravel 5 : Is it possible to use __construct() and Illuminate\Http\Request for testcase classes?

I'm trying dependency injection for test cases, wondering if it is possible to do that for testing.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class PageController extends Controller
{
    protected $request;
    protected $user;

public function __construct(Request $request, User $user)
{
    $this->user    = $user;
    $this->request = $request;
}

This is how I usually do dependency injection. For example, the following line gets an array instance of all the users.

$users = $this->user->all();

I'd like to do the same thing for 'TestCase'. Here is an excerpt of the code.

use App\User;
use Illuminate\Http\Request;

class ViewTest extends TestCase
{
    protected $request;
    protected $user;

public function __construct(Request $request, User $user)
{
    $this->user    = $user;
    $this->request = $request;
}

This causes the following error.

PHP Fatal error: Uncaught TypeError: Argument 1 passed to ViewTest::__construct() must be an instance of Illuminate\Http\Request, none given, called in phar

It sounds like that __construct() must be an instance of Request, but I don't understand what it actually means, since this code works in, let's say controller classes.

I've searched Laravel's documentation, but I'm not really sure if it's possible to do dependency injection for testing.

I'd appreciate if you would give any advice.



via Chebli Mohamed

Is splitting an index action into multiple ones a restful-friendly approach?

I need to display two different index pages to two different user groups. For example, a regular user should see one page, and a privileged user - another one. I see two ways of approaching this issue:

One index action with conditionals:

public function index()
{
    // view for privileged users
    if(request()->user()->hasRole('privileged')){
        return view('index_privileged');
    }

    // view for regular users
    if(request()->user()->hasRole('regular')){
        return view('index_regular');
    }

    return redirect('/');
}

Multiple actions:

public function index_privileged()
{
    return view('index_privileged');
}

public function index_regular()
{
    return view('index_regular');
}

Which approach is more "restful-friendly" and generally better?



via Chebli Mohamed

Image is saving as tmp file in database laravel

Before explaining the problem. Let me show the controller function:

public function storePost(IdeaRequest $request)
{
   $idea = new Idea();
   $idea->idea_title       = $request->input('idea_title');
   $idea->user_id          = $request->input('user_id');
   $idea->idea_image       = $request->file('idea_image')->move('publicPages\images')->getClientOriginalName();
   $idea->idea_info        = $request->input('idea_info');
   $idea->selection        = $request->input('selection');
   $idea->idea_location    = $request->input('idea_location');
   $idea->idea_goal        = $request->input('idea_goal');
   $idea->idea_description = $request->input('idea_description');
   $idea->save();
   session()->flash('flash_message', 'Your idea has been submitted for Review');
   return back();
}

It stores the image as .tmp file. Things I have tried out

  • guessExtension(), It just returns the extension name and does not even store the image.

  • getClientOriginalName(), it throws an error; getClientOriginalName method is not defined. I have searched the method and it is in there. used its namespace Symfony\Component\HttpFoundation\File\UploadedFile. it did not work either.

  • Tried different things out from stackoverflow, Nothing has worked for me till now. In other words, i have invested a lot of time to solve this problem but nothing worked. Any help would highly be appreciated.



via Chebli Mohamed

Class 'Users' Not found Laravel 4.2 Users::all();

I am just trying to have my users table printed out onto a page. I am getting a Class 'Users' Not found in Laravel 4.2 - I have dump-autoloaded and clear-compiled.

My users.php is:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password', 'remember_token');
}

My controller file reads (ive redacted code -- the issue is 100% this portion of code, as it works if I just pass messages to the view:

<?php

class SearchController extends BaseController {

public function search()
{
    $search = Input::get("Search_Input");
    $search_terms = explode(",", $search);
    $search_query_type = Input::get("search_type");
    $search_type = 'null';

    if ($search_type === "Rep_Name") {
       $users = Users::all();
       return Redirect::to('/search')->with('users', $users);
     }
}

My search view has this code:

    @foreach($users as $name)
        
    @endforeach

My database has a users table and a Name row.

The laravel.log error I get is:

[2016-04-28 19:32:30] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Users' not found' in /home3/circates/public_html/jon/repform/app/controllers/SearchController.php:50
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
#1 {main} [] []



via Chebli Mohamed

Can't access request parameters inside a middleware

I want to retrieve an id in the custom middleware that runs after following route: /quiz/1/edit. I expect, that the $route should contain 'id' => 1, but it doesn't. Why is that?

public function handle($request, Closure $next)
{
    dd($request->all()); // --> []
    . . .
}

The route declaration:

Route::resource('quiz', 'QuizzesController');



via Chebli Mohamed

How to check if user owns a record with Entrust?

I want to allow users to CRUD only posts they own. I would like not to create a new middleware, but to leverage the existing ones instead. So, Can Entrust's default middlewares be extended to fit this purpose?

class PostsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:blogger|owner'); // <--
    }

    ...
}



via Chebli Mohamed

Test external package in Laravel

In my package I have a lot of facade calls and IoC container resolutions. None of these work outside of laravel framework infrastructure.

So how do I unit-test my package?



via Chebli Mohamed

How to use Entrust middleware inside a controller?

It is described in Entrust docs how to use middlewares with routes, but I could not find any instructions regarding their usage in controllers.

An example of what I want to do:

class QuizzesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:admin|root'); // <---
    }

    ...
}

As you understand, this code does not work. How can I achieve the illustrated behavior?



via Chebli Mohamed

Getting error while inserting data to mysql database

While Inserting data to mysql database i'm getting the error coming below, and as of some previous question's answer on stackoverflow i put protected $fillable in my model file but still showing error.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`article_id`) REFERENCES `users` (`id`)) (SQL: insert into `articles` (`article_head`, `article_body`) values (abkskfbasfbv, zbfvaksdvaskdvjsdc
))

Article.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
  protected $fillable = [
      'article_head', 'article_body',
  ];
    public $timestamps = false;
}

migration file

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function(Blueprint $table)
        {
            $table->increments('article_id');
            $table->string('article_head', 500);
            $table->string('article_body', 10000);
            $table->dateTime('created_on');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('articles');
    }

}

2016_04_27_181606_add_foreign_keys_to_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddForeignKeysToArticlesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->foreign('article_id', 'articles_ibfk_1')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('RESTRICT');
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->dropForeign('articles_ibfk_1');
        });
    }

}



via Chebli Mohamed

Laravel 5 download MSI response crashes

I am having a problem with downloading a .msi file from the server. The moment I open up the link, my command line crashes directly (I assume my server as well, cause I have to boot it up again each time it crashes).

While .msi crashes, I have tried doing it with a .pkg file, and it downloads with no problem!

Does anyone have an idea what is going on? Or do I have to put something extra for downloading a .msi file?

Here is my code in the routing:

// Instant crash
Route::get('/download/windows', function(){

   return response()->download(storage_path() . "\\Game\\game.msi");

});

// Works perfectly
Route::get('/download/mac', function(){

   return response()->download(storage_path() . "\\Game\\game.pkg");

});



via Chebli Mohamed

laravel mongodb how to change _id to id on output?

I want to have _id in the database but want to output id when doing a query.

How can I achieve it?



via Chebli Mohamed

laravel how to database seed with two different classes that have the same collection name?

I am trying to create a semi Single Table Inheritance using Eloquent (I am using MongoDB but that doesn't matter):

I have a class Person that has the collection people. The person class has a role attribute. One of the roles is 'athlete'.

Then, I created another class Athlete that extends Person. I have set up class like the following:

 class Athlete extends Person {
      protected $collection = 'people';

      public $role = 'athlete';
 }

When I do database seed to both generic person and athlete. Here is my model factory:

$factory->define(App\Modules\User\Models\User::class, function (Faker\Generator $faker) {
    $password = str_random(10);
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt($password),
        'password_raw' => $password,
        'remember_token' => str_random(10),
        'role' => 'admin'
    ];
});

$factory->define(App\Modules\Athletes\Models\Athlete::class, function (Faker\Generator $faker) {
    $password = str_random(10);
    $sports = ['Triathlon', 'Wrestling', 'Swimming', 'Archery', 'Rowing', 'Tennis', 'Road cycling', 'Diving', 'Boxing', 'Badminton'];
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt($password),
        'remember_token' => str_random(10),
        'sports' => $sports[$faker->biasedNumberBetween(0, 9)],
        'role' => 'athlete'
    ];
});

When I do php artisan db:seed the output shows that both seed classes UserDatabaseSeeder and AthleteDatabaseSeeder is seeded. However, when I test the database, it only shows 10 values from athlete seeder. Here are the seeders:

class AthleteDatabaseSeeder extends Seeder
{

    public function run()
    {
        Model::unguard();
        factory(Athlete::class, 10)->create();
        Model::reguard();
    }
}

class UserDatabaseSeeder extends Seeder {

    public function run() {
        Model::unguard();
        factory(User::class, 10)->create();
        Model::reguard();
    }
}

How can I make the seeder work?

Thank you!



via Chebli Mohamed

Undefined offset:1- Laravel Error exception

I Know there are several links referred to this error but still I am unable to find the exact solution of my issue. I have two check-boxes named admin_menu_id[] and admin_sub_menu_id[] whose value i want to insert into database. So far I have done this:-

View page

 @if(is_array($roledatas) && count($roledatas)>0)
    <?php $count = 1;?>
    @foreach($roledatas as $roleKey=>$roleVal)
        <ul id="package_" class="accordion-toggle parentclasstr" data-toggle="collapse" data-parent="#OrderPackages" data-target=".packageDetails">

            <li><input type="checkbox" id="menuChk" value= "<?php echo $id = $roleVal['id']; ?>" name="admin_menu_id[]" /><strong></strong></li>
            <li><i class="indicator glyphicon glyphicon-chevron-up pull-right"></i></li>                        

        @if(isset($roleVal['child']) && is_array($roleVal['child']) && count($roleVal['child'])>0)
            @foreach($roleVal['child'] as $childKey=>$childVal)
        <ul class="hiddenRow collapse packageDetails" bgcolor="#C1C1C1">

            <li><input type="checkbox" id="submenuChk" value="<?php echo $id = $childVal['id']; ?>" name="admin_sub_menu_id[]" /></li>
            <li></li>
        </ul>
            @endforeach
        @endif
        </ul>
        <?php $count++; ?>
    @endforeach
@endif

Controller:-

$data = $request->all();
    $user_type_id = $data['user_type_id'];
    $admin_menu_id = $data['admin_menu_id'];
    $admin_sub_menu_id = $data['admin_sub_menu_id'];

    for ($i = 0; $i < count($data['admin_sub_menu_id']); $i++)
    {
        $role = new RoleMenu;
        $role->user_type_id = $user_type_id;
        $role->admin_menu_id = $admin_menu_id[$i];
        $role->admin_sub_menu_id = $admin_sub_menu_id[$i];
        $role->save();
    }

It inserts data when i check one admin_menu_id checkbox and one admin_sub_menu_id checkbox but when try to check more than one it throws an error of Undefined Offset. I am completely new to laravel and these array games!! Kindly help me out on this.



via Chebli Mohamed

How to limit the number of simultaneous sessions in Laravel 5?

I'm building a web-app using Laravel 5.2 and I need to limit number of simultaneous user sessions. Is this possible using default file based session driver? Or should I use database / redis / whatever driver? The question is what could be the simplest approach when I only care about max connected users / sessions and not the performance?



via Chebli Mohamed

integrate Dropzone.js in Laravel 5.2

In my laravel 5.2 project I need to create a multi file upload area. I choose Dropzone.js Now my problem is how to use this plugin with laravel.

this is my view:

<div class="tab-pane" id="tab_2">
                <div class="box-body">
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">Facebook:</label>
                        <div class="col-sm-10">
                            <input type="text" name="facebook" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">Twitter:</label>
                        <div class="col-sm-10">
                            <input type="text" name="twitter" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="video" class="col-sm-2 control-label">Video:</label>
                        <div class="col-sm-10">
                            <input type="text" name="video" class="form-control">
                        </div>
                    </div>

                    <!--File Upload-->


        <div class="dropzone" id="dropzoneFileUpload">
        </div>



 <script type="text/javascript">
        var baseUrl = "";
        var token = "";
        Dropzone.autoDiscover = false;
         var myDropzone = new Dropzone("div#dropzoneFileUpload", {
             url: baseUrl+"/dropzone/uploadFiles",
             params: {
                _token: token
              }
         });
         Dropzone.options.myAwesomeDropzone = {
            paramName: "file",
            maxFilesize: 2, // MB
            addRemoveLinks: true,
            accept: function(file, done) {

            },
          };
     </script>

my controller:

    public function store(SpotFormRequest $request) {
     $user = Auth::user();
     $role = $user->role;
     if($role === 'manager'){
         $idagent = 1;
         $idmanager = $user->id;
     }
     else{
         $idagent=$user->id;
         $idmanager=0;
     }


    $spot = new Spot(array(
        'agent_id'=>$idagent,
        'manager_id'=>$idmanager,
        'name' => $request->get('spotname'),
        'address' => $request->get('address'),
        'zip' => $request->get('zip'),
        'city'=>$request->get('city_id'),
        'phone' => $request->get('phone'),
        'mobile' => $request->get('mobile'),
    ));
    $spot->save();

    return redirect('/administrator/spot-new')->with('status', 'Your spot has been created!');
}

I need to integrate the upload in the controller.



via Chebli Mohamed

How to get list of users in laravel 5

I am working over a project. I have required some basic values in different routes. e.g. show the list of users, locations, products in different pages/routes. So i wanted to create a common method for these like where i want to show list of users i will call the method for user and pass this list to view.

I've tried the following method

$usersArr = User::where('loc_id', session('organization'))->where('status', '!=', 'Deleted')->orderBy('id', 'desc')->lists('username', 'id');

So i wanted to know which is best place to define these type of methods. Should i define this in Model,Controller or create some type of common functions.



via Chebli Mohamed

configure 1and1 mail on google cloud platform with laravel 5

I have setup an instance in google cloud platform. I am running laravel 5.2 project on that instance. Everything is working good but i am facing some issues while configuring 1and1 mail.

I know that google cloud platform is blocked the 587,465 and 25 port by default and we can setup some vpn which will help to remove this restriction. But i don't want to go in that way because it would have security problems.

I have tried to send email through smtp and mail driver. I am getting connection failure error through smtp driver, and through mail driver, it shows that email is sent but i am not getting the email in my inbox. Here is my .env file for mail driver settings for 1and1. I have also tried 25 port also.

MAIL_DRIVER=mail
MAIL_HOST=auth.smtp.1and1.co.uk
MAIL_PORT=587
MAIL_USERNAME=test@mydomain.com
MAIL_PASSWORD=pass
MAIL_ENCRYPTION=tls

Can you please help me to configure it?



via Chebli Mohamed

Laravel 5, can't get the ID of the just saved model, when using UUID

I'm using Laravel Eloquent for my posts table and using the UUID for my table's primary key. But after saving the model I can't get the ID of it, although all the values are correctly inserted in database.

$post = new App\Post();
$post->uuid  = \Webpatser\Uuid\Uuid::generate();
$post->save();
dd($post->uuid); //return null or 0



via Chebli Mohamed

Laravel Repository pattern and many to many relation

In our new project we decided to use hexagonal architecture. We decided to use repository pattern to gain more data access abstraction. We are using command bus pattern as service layer. In our dashboard page we need a lot of data and because of that we should use 3 level many to many relations (user -> projects -> skills -> review) and also skills should be active(status=1).

The problem rises here, where should i put this?

  1. $userRepository->getDashboardData($userId).

2.$userRepository->getUser($userId)->withProjects()->withActiveSkills()->withReviews();

3.$user = $userRepository->getById(); $projects = $projectRepository->getByUserId($user->id); $skills = $skillRepository->getActiveSkillsByProjectsIds($projectIds);

In this case, I couldn't find the benefits of repository pattern except coding to interface which can be achived with model interfac. I think solution 3 is prefect but it adds a lot of work.



via Chebli Mohamed

Laravel 5.1: Auth::logout() is not working and BindingResolutionsException is not instantiable error

I'm new in laravel and I try to build a simple Authentication. All the things works fine except when using AuthController's action to log out, it just simply doesn't work. I have a nav bar which checks for Auth::check() and it doesn't change after calling the log out action and it stocks in home page. but after making few changes like deleting this manual logout code in SessionController:

public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

and changing the rout from this:

Route::get('logout', 'SessionsController@logout');

to this:

Route::get('auth/logout', 'Auth\AuthController@logout');

it throws this error:

BindingResolutionException in Container.php line 749: Target [Illuminate\Contracts\Auth\Registrar] is not instantiable. 

I have this route inside the routes.php file:

Route::get('auth/logout', 'Auth\AuthController@logout');

and my AuthController is the controller that laravel providing us.

my SessionsController that handled logout before the changes but actually not work either is:

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SessionsController extends Controller
{
    /**
     * Create a new sessions controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the login page.
     *
     * @return \Response
     */
    public function login()
    {
        return view('auth.login');
    }

    /**
     * Perform the login.
     *
     * @param  Request  $request
     * @return \Redirect
     */
    public function postLogin(Request $request)
    {
        $this->validate($request, ['username' => 'required|exists:users', 'password' => 'required']);

        if ($this->signIn($request)) {
            flash('Welcome back!');

            return redirect()->intended('dashboard');

        }

        flash('Could not sign you in.');

        return redirect()->back();
    }

    /**
     * Destroy the user's current session.
     *
     * @return \Redirect
     */
    public function logout()
    {
        Auth::logout();
        Session::flush();
        return redirect()->intended('login');
    }

    /**
     * Attempt to sign in the user.
     *
     * @param  Request $request
     * @return boolean
     */
    protected function signIn(Request $request)
    {
        return Auth::attempt($this->getCredentials($request), $request->has('remember'));
    }

    /**
     * Get the login credentials and requirements.
     *
     * @param  Request $request
     * @return array
     */
    protected function getCredentials(Request $request)
    {
        return [
            'username' => $request->input('username'),
            'password' => $request->input('password'),
            'verified' => true
        ];
    }


}

And here is the AuthController __construct method:

public function __construct(Guard $auth, Registrar $registrar)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        $this->middleware('guest', ['except' => ['logout', 'getLogout']]);

    }

Please help me as soon as possible. Any help would be appreciated.



via Chebli Mohamed