EzDevInfo.com

laravel-5 interview questions

Top laravel-5 frequently asked interview questions

What's the correct way to set ENV variables in Laravel 5?

In laravel 4 we had:

$env = $app->detectEnvironment(array(
    'local' => array('homestead')
));

by default.

But in laravel 5 it's changed to:

$env = $app->detectEnvironment(function()
{
    return getenv('APP_ENV') ?: 'production';
});

Also, they have excluded .env.* line in .gitignore, now it has:

.env

And added file .env.example:

APP_ENV=local
APP_KEY=SomeRandomString
DB_USERNAME=homestead
DB_PASSWORD=homestead

So, if i have more than 2 environments, do i have to set all of them in a single .env file now? E.g.:

APP_ENV=local
DB_PASSWORD=123

APP_ENV=alpha
DB_PASSWORD=456

If i would have no .env file, how laravel will know what environment i am using?


Source: (StackOverflow)

Laravel Model Events - I'm a bit confused about where they're meant to go

So the way I see it is that a good Laravel application should be very model- and event-driven.

I have a Model called Article. I wish to send email alerts when the following events happen:

  • When an Article is created
  • When an Article is updated
  • When an Article is deleted

The docs say I can use Model Events and register them within the boot() function of App\Providers\EventServiceProvider.

But this is confusing me because...

  • What happens when I add further models like Comment or Author that need full sets of all their own Model Events? Will the single boot() function of EventServiceProvider just be absolutely huge?
  • What is the purpose of Laravel's 'other' Events? Why would I ever need to use them if realistically my events will only respond to Model CRUD actions?

I am a beginner at Laravel, having come from CodeIgniter, so trying to wrap my head around the proper Laravel way of doing things. Thanks for your advice!


Source: (StackOverflow)

Advertisements

Upgrading to Laravel 5.2 invalidates all sessions

Upgrading from Laravel 5.1.17 to 5.2. My config/auth.php originally contained:

'driver' => 'eloquent',
'model'  => 'Project\User',
'table'  => 'users',

New file is the same as the default, except with the updated namespace.

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Project\User::class,
    ],
],

My env SESSION_DRIVER is redis. I did not clear anything from Redis. (Note, this also happened in my other projects where driver was file, but I didn't care about it as much for them.)

I have two branches, L5.2 and master (which is on 5.1.17). After switching branches, I simply run composer install

If I login on master, then switch to L5.2, I am logged out
If I switch back to master, I am logged back in
If I login on L5.2, then switch to master, I stay logged in
If I switch back to L5.2, I stay logged in

I'm hesitant to upgrade if it's going to invalidate all of my users' sessions and force them to login again. Is there a way to avoid this?

The only other files that were modified were composer.json, composer.lock, app/Exceptions/Handler.php, and config/app.php; nothing that touched Auth.


Source: (StackOverflow)

Laravel 5 Route Group and Basic(/) GET Route within group

I am working on a Laravel 5.0 Web application with Admin panel. I am facing an issue with Routes. I have Grouped Admin Routes like below,

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['user.admin']], function () {
    Route::get('login', [
        'as' => 'admin.login',
        'uses' => 'AuthController@getLogin'
    ]);
    Route::get('logout', [
        'as' => 'admin.login',
        'uses' => 'AuthController@getLogout'
    ]);
    Route::post('login', 'AuthController@postLogin');
});

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['user.admin','auth', 'admin.acl']], function () {

    Route::get('dashboard', [
        'as'         => 'admin.dashboard',
        'uses'       => 'DashboardController@index',
        'permission' => 'admin_dashboard'
    ]);

    //Image Handler
    Route::get('images/{size}/{name?}',[
        'as'   => 'admin.images',
        'uses' => 'ImagesController@images'
    ]);

    Route::resource('user', 'UsersController');

    ........   

});

Things are working fine. I can use following without any problem,

http://domain.com/admin/dashboard
http://domain.com/admin/login

But I want

http://domain.com/admin

to display login page or redirect to

http://domain.com/admin/login

so I changed my first group to following,

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['user.admin']], function () {

    Route::get('/', [        
        'uses' => 'AuthController@getLogin'
    ]);
    Route::get('login', [
        'as' => 'admin.login',
        'uses' => 'AuthController@getLogin'
    ]);
    Route::get('logout', [
        'as' => 'admin.login',
        'uses' => 'AuthController@getLogout'
    ]);
    Route::post('login', 'AuthController@postLogin');
});

Now When I access

http://domain.com/admin

I get 'This webpage has a redirect loop' in chrome. Is it possible in Route group? if not how to do this with .htaccess?

UPDATE

Below is the handle method of a Middleware user.admin. Which does nothing but changes underlying model for authentication.

    public function handle($request, Closure $next)
    {
        \Config::set('auth.table', 'admins');
        \Config::set('auth.model', 'App\DB\Admin\Admin');

        \Config::set('session.cookie', 'admin_session');
        \Config::set('session.path', '/admin/');

        return $next($request);
    }

UPDATE

This is amazing, following works

http://domain.com/index.php/admin

I have not touched default .htaccess supplied by laravel 5.0, which is below,

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I have almost 60-70 routes, and all of them works without index.php accept in above scenario I needed index.php.


Source: (StackOverflow)

Laravel 5 package development

I am having trouble to create package in Laravel 5 as workbench has been removed.

As in this thread (How create package in Laravel 5?), Goldorak suggest that we have to create our own package structure ourselves.

So, how can I create the workbench manually and get everything ready for package development?


Source: (StackOverflow)

Laravel 5.1 Eloquent ORM randomly returning incorrect relationship - *major update*

I have a Laravel app that powers an ecommerce website with moderate traffic. This website allows people to place orders via the frontend, but it also has backend functionality for taking orders over the phone via a call centre.

An order is related to a customer, and a customer can optionally be a user - a user being someone with a login to the frontend. A customer with no user account is only ever created as a result of an order being taken via the call centre.

The issue I have encountered is very odd, and I believe might be some kind of Laravel bug.

It only occurs very occasionally, but what is happening is that when an order is taken via the call centre for a customer with no user account, an order confirmation is being sent out to a random user - literally random, as far as I can tell, just plucked out of the database despite no relation in the data.

These are the relevant parts of the models in the project:

class Order extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

class Customer extends Model
{
    public function orders()
    {
        return $this->hasMany('App\Order');
    }

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

class User extends Model
{ 
    public function customer()
    {
        return $this->hasOne('App\Customer');
    }
}

These are the database migrations for the above (edited for brevity):

   Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->boolean('active');
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('customers', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('user_id')->nullable->index();
        $table->string('first_name');
        $table->string('last_name');
        $table->string('telephone')->nullable();
        $table->string('mobile')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('orders', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('payment_id')->nullable()->index();
        $table->integer('customer_id')->index();
        $table->integer('staff_id')->nullable()->index();
        $table->decimal('total', 10, 2);
        $table->timestamps();
        $table->softDeletes();
    });

The logic that sends the order confirmation is within an event handler that gets fired after the order has been paid.

Here is the OrderSuccess event (edited for brevity):

namespace App\Events;

use App\Events\Event;
use App\Order;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;


class OrderSuccess extends Event
{
    use SerializesModels;

    public $order;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

As can be seen, this event is passed an Order model object.

Here is the event handler (edited for brevity):

/**
 * Handle the event.
 *
 * @param  OrderSuccess  $event
 * @return void
 */
public function handle(OrderSuccess $event)
{
    // set order to paid
    $order = $event->order;
    $order->paid = date('Y-m-d H:i:s');
    $order->save();

    if(!is_null($order->customer->user)) {

        App_log::add('customer_order_success_email_sent', 'Handlers\Events\OrderSuccessProcess\handle', $order->id, print_r($order->customer, true).PHP_EOL.print_r($order->customer->user, true));

        // email the user the order confirmation
        Mail::send('emails.order_success', ['order' => $order], function($message) use ($order)
        {
            $message->to($order->customer->user->email, $order->customer->first_name.' '.$order->customer->last_name)->subject('Order #'.$order->id.' confirmation');
        });
    }

}

There is a check to see if the $order->customer->user object is not null and, if true, an order confirmation is sent. If it is null (which it frequently is), then no confirmation is sent.

As can be seen from the above, I added a log to record the objects when an email is sent. Here is an example of an erroneous one (again, truncated for brevity):

App\Customer Object
(
[attributes:protected] => Array
    (
        [id] => 10412
        [user_id] => 
        [first_name] => Joe
        [last_name] => Bloggs
        [telephone] => 0123456789
        [created_at] => 2015-09-14 13:09:45
        [updated_at] => 2015-10-24 05:00:01
        [deleted_at] => 
    )

[relations:protected] => Array
    (
        [user] => App\User Object
            (
                [attributes:protected] => Array
                    (
                        [id] => 1206
                        [email] => johndoe@whoknows.com
                        [password] => hashed
                        [remember_token] => 
                        [created_at] => 2015-09-19 09:47:16
                        [updated_at] => 2015-09-19 09:47:16
                        [deleted_at] => 
                    )
            )

    )

[morphClass:protected] => 
[exists] => 1
[wasRecentlyCreated] => 
[forceDeleting:protected] => 
)

App\User Object
(
[attributes:protected] => Array
    (
        [id] => 1206
        [email] => johndoe@whoknows.com
        [password] => hashed
        [remember_token] => 
        [created_at] => 2015-09-19 09:47:16
        [updated_at] => 2015-09-19 09:47:16
        [deleted_at] => 
    )

[morphClass:protected] => 
[exists] => 1
[wasRecentlyCreated] => 
[forceDeleting:protected] => 
)

As you can see, there is no user_id for Customer, and yet Laravel has returned a User object.

What is more, if I manually fire the exact same OrderSuccess event, the above is not reproducible - it does not send the email, and it does not load a User object.

As I said before, this issue is happening very infrequently - there are on average about 40 orders a day via the call centre for customers with no user account, and the highlighted issue might only occur once or twice a week.

I'm not familiar enough with Laravel to know what might be the issue here - is it some form of model caching, a problem with Eloquent ORM, or some other gremlin in the system?

Any ideas appreciated - I may post this problem in the Laravel github issue tracker if it appears to be some form of bug.

Update Relating to some of the answers / comments put forward, I have tried to remove any potential Eloquent ORM issues, to retrieve the data manually, like so:

$customer = Customer::find($order->customer_id);
$user = User::find($customer->user_id);

if(!is_null($user)) {
    // send email and log actions etc
}

The above is still producing the same random results - unrelated users are being retrieved even when the customer has no user_id (it's NULL in this instance).

Update 2 As the first update did not help in any way, I reverted to using the original Eloequent approach. To try another solution, I took my event code out of the event handler, and placed it in my controller - I was previously firing by OrderSuccess event using Event::fire(new OrderSuccess ($order));, and instead I commented this line out and just placed the event handler code in the controller method:

$order = Order::find($order_id);

//Event::fire(new OrderSuccess ($order));

// code from the above event handler
$order->paid = date('Y-m-d H:i:s');
$order->save();

if(!is_null($order->customer->user)) {

    App_log::add('customer_order_success_email_sent', 'Handlers\Events\OrderSuccessProcess\handle', $order->id, print_r($order->customer, true).PHP_EOL.print_r($order->customer->user, true));

    // email the user the order confirmation
    Mail::send('emails.order_success', ['order' => $order], function($message) use ($order)
    {
        $message->to($order->customer->user->email, $order->customer->first_name.' '.$order->customer->last_name)->subject('Order #'.$order->id.' confirmation');
    });
}

The above change has been on the production site for over a week now - and since that change, there has not been a single instance of the issue.

The only possible conclusion I can reach is some kind of bug in the Laravel event system, somehow corrupting the passed object. Or could something else be at play?

Update 3 It seems I was premature to state that moving my code outside the event fixed the issue - in fact, via my logging, in the last 2 days I can see some more incorrect order confirmation were sent out (a total of 5, after almost 3 weeks of no issues).

I noticed that the user ids that had received the rogue order confirmations appeared to be incrementing (not without gaps, but still in ascending order).

I also noticed that each of the problem orders had been paid for via cash and account credit - most are cash only. I looked further into this, and the user ids are actually the ids of the related credit transactions!

The above is the first cast iron breakthrough in trying to resolve this issue. On closer inspection, I can see that the issue is still random - there are quite a few (at least 50%) orders that have been paid via account credit for customer's with no user account, but that have not caused incorrect emails to be sent out (despite the associated credit transaction id having a user id match).

So, the problem is still random, or seemingly so. My credit redemption event is triggered like so:

Event::fire(new CreditRedemption( $credit, $order ));

The above is called just prior to my OrderSuccess event - as you can see, both events are passed the $order model object.

My CreditRedemption event handler looks like this:

public function handle(CreditRedemption $event)
{
    // make sure redemption amount is a negative value
    if($event->credit < 0) {
        $amount = $event->credit;
    }
    else {
        $amount = ($event->credit * -1);
    }

    // create the credit transaction
    $credit_transaction = New Credit_transaction();
    $credit_transaction->transaction_type = 'Credit Redemption';
    $credit_transaction->amount = $amount; // negative value
    $credit_transaction->customer_id = $event->order->customer->id;
    $credit_transaction->order_id = $event->order->id;

    // record staff member if appropriate
    if(!is_null($event->order->staff)) {
        $credit_transaction->staff_id = $event->order->staff->id;
    }

    // save transaction
    $credit_transaction->save();

    return $credit_transaction;
}

The $credit_transaction->save(); is generating the id in my credit_transactions table that is somehow being used by Laravel to retrieve a user object. As can be seen in the above handler, I'm not updating my $order object at any point.

How is Laravel using (remember, still randomly, some < 50% of the time) the id of my newly created $credit_transaciton to populate the $order->customer->user model object?


Source: (StackOverflow)

Multi-tiered comment system Laravel

I'm having difficulty with blade recursive partial views. Everything works for the most part with the exception of recursion in the comment.blade.php file.

I know I need to use a foreach around the @include('articles.comments.comment', $comment) to call itself again, but I'm not sure how to call for it.

article_comments table:

id
message
user_id
parent_id
created_at
updated_at

app\Article.php Class:

class Article extends Model {

    protected $table = 'articles';

    protected $fillable = [
        'category',
        'title',
        'permalink',
        'synopsis',
        'body',
        'source',
        'show_author',
        'published_at'
    ];

    protected $dates = ['published_at'];

    public function scopePublished($query)
    {
        $query->where('published_at', '<=', Carbon::now());
    }

    public function setPublishedAtAttribute($date)
    {
        $this->attributes['published_at'] = Carbon::parse($date);
    }

    public function comments()
    {
        return $this->hasMany('App\Comments')->where('parent_id', 0);
    }

}

app\Comments.php Class:

class Comments extends Model {

    protected $table = 'article_comments';

    protected $fillable = [
        'parent_id',
        'message',
    ];

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

    public function children()
    {
        return $this->hasMany('App\Comments', 'parent_id');
    }

    public function countChildren($node = null)
    {
        $query = $this->children();
        if (!empty($node)) {
            $query = $query->where('node', $node);
        }

        $count = 0;
        foreach ($query->get() as $child) {
            // Plus 1 to count the direct child
            $count += $child->countChildren() + 1; 
        }
        return $count;
    }

}

app\Http\Controllers\ArticlesController.php:

public function show($permalink)
{
    $article = Article::where('permalink', '=', $permalink)->with('comments','comments.author','comments.children')->first();
    if ($article != null) {
        $comments = $article->comments;
        return view('articles.show', compact('article','comments'));
    } else {
        return redirect('/')->with('error', 'This article does not exist.');
    }
}

resources\views\articles\show.blade.php

@if (count($comments) > 0)
    <ul>
    @foreach ($comments as $comment)
        @include('articles.comments.comment', ['comment'=>$comment])
    @endforeach
    </ul>
@else
    no comments
@endif

resources\views\articles\comments\comment.blade.php

<li>
    {{ $comment->message }}

    @if (count($comment->children) > 0)
        <ul>
        @foreach ($comment->children as $child)
            @include('articles.comments.comment', ['comment'=>$child])
        @endforeach
        </ul>
    @endif
</li>

Current error:

Invalid argument supplied for foreach() (View: /var/www/dev.example.com/resources/views/articles/comments/comment.blade.php) (View: 

Source: (StackOverflow)

Laravel 5 needs index.php using Apache virtual host

When I load pages that are not root, the page won't load without index.php before the route. The error I get:

 Not Found

 The requested URL /login was not found on this server.

 Apache/2.4.7 (Ubuntu) Server at mydomain.com Port 80

To start with I have a virtual host file containing:

//also tried adding DirectoryIndex here before <directory>
<directory /var/www/mydomain.com>
    DirectoryIndex index.php
    AllowOverride ALL
</directory>

and a .htacces in my public with :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

I have another domain with the same .htaccess and appache config on the same server and it works fine. Also I did restart apache. If I use phpinfo on my index.php/route page I see at Loaded Modules:

mod_rewrite mod_setenvif 

When running the website localy with xampp everything works fine. For hours i'm trying now but I can't fix it or find any error (logs are empty) or any solutions that I haven't tried yet.

Edit:

Im using Ubuntu Ubuntu 14.04 x64 on a digital ocean VPS. And I tried turning it on and off again (as suggested). PHP Version 5.5.9-1ubuntu4.9. I followed this tutorial to config everything (except the direcoty part). I changed the location of the apache log and a file error.log is created on the given directory but no errors are in it.

My currently appache config is :this (i've triple checked the white parts where the domain name is).

When I run apache2ctl -t D DUMP_VHOSTS I get

enter image description here

this looks fine to me, also tried disabling the default config but it didnt help.

Note: i've replaced my real domain with mydomain.com in reality I use my real domain on these spots.

Thought how do I know for sure that the conf file im editing is the one being used by the domain?


Source: (StackOverflow)

Laravel 5 Function () not found

I'm putting together a site which has a protected section where users must be logged in to access. I've done this in Laravel 4 without too much incident. However, for the life of me I cannot figure out why I can't get it to work in Laravel 5(L5).

In L5 middleware was/were introduced. This changes the route file to:

Route::get('foo/bar', ['middleware'=>'auth','FooController@index']);
Route::get('foo/bar/{id}', ['middleware'=>'auth','FooController@show']);

The route works fine as long as the middleware is not included.

When the route is accessed with the middleware however the result is not so much fun.

Whoops, looks like something went wrong.

ReflectionException in Route.php line 150:

Function () does not exist

Any insight, help, and/or assistance is very appreciated. I've done the Google circuit and couldn't find anything relevant to my current plight. Thanks in advance.


Source: (StackOverflow)

Laravel 4/5 search form like

I have a search form and functions, all done. Just to ask, is it possible to do it in Eloquent a query like this:

SELECT * FROM players WHERE name LIKE '%".$name."%'

To display some possible matching names. My current controller function:

    public function search()
{
    $name = Input::get('character');
    $searchResult = Player::where('name', '=', $name)->paginate(1);
    return View::make('search.search')
            ->with('name', $name)
            ->with('searchResult', $searchResult);
}

And my view:

    <form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController@search') }}" method="get">
    <div class="input-append spancustom">
        <input type="text" class="search-query" name="character" placeholder="Character/guild name">
        <button type="submit" class="btn"><i class="icon-search"></i></button>
    </div>
</form>

Thanks in advance.


Source: (StackOverflow)

Laravel 5: Type-hinting a FormRequest class inside a controller that extends from BaseController

I have a BaseController that provides the foundation for most HTTP methods for my API server, e.g. the store method:

BaseController.php

/**
 * Store a newly created resource in storage.
 *
 * @return Response
 */
public function store(Request $request)
{
    $result = $this->repo->create($request);

    return response()->json($result, 200);
}

I then extend on this BaseController in a more specific controller, such as the UserController, like so:

UserController.php

class UserController extends BaseController {

    public function __construct(UserRepository $repo)
    {
        $this->repo = $repo;
    }

}

This works great. However, I now want to extend UserController to inject Laravel 5's new FormRequest class, which takes care of things like validation and authentication for the User resource. I would like to do this like so, by overwriting the store method and using Laravel's type hint dependency injection for its Form Request class.

UserController.php

public function store(UserFormRequest $request)
{
    return parent::store($request);
}

Where the UserFormRequest extends from Request, which itself extends from FormRequest:

UserFormRequest.php

class UserFormRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'  => 'required',
            'email' => 'required'
        ];
    }

}

The problem is that the BaseController requires a Illuminate\Http\Request object whereas I pass a UserFormRequest object. Therefore I get this error:

in UserController.php line 6
at HandleExceptions->handleError('2048', 'Declaration of Bloomon\Bloomapi3\Repositories\User\UserController::store() should be compatible with Bloomon\Bloomapi3\Http\Controllers\BaseController::store(Illuminate\Http\Request $request)', '/home/tom/projects/bloomon/bloomapi3/app/Repositories/User/UserController.php', '6', array('file' => '/home/tom/projects/bloomon/bloomapi3/app/Repositories/User/UserController.php')) in UserController.php line 6

So, how can I type hint inject the UserFormRequest while still adhering to the BaseController's Request requirement? I cannot force the BaseController to require a UserFormRequest, because it should work for any resource.

I could use an interface like RepositoryFormRequest in both the BaseController and the UserController, but then the problem is that Laravel no longer injects the UserFormController through its type hinting dependency injection.


Source: (StackOverflow)

laravel No supported encrypter found. The cipher and / or key length are invalid

I am building a project using Laravel. It was working fine on localhost, but when I upload it to the server (the server has comodo ssl installed), I receive the following error:

RuntimeException in EncryptionServiceProvider.php line 29:
No supported encrypter found. The cipher and / or key length are invalid
in EncryptionServiceProvider.php line 29
at EncryptionServiceProvider->Illuminate\Encryption\{closure}(object(Application), array()) in Container.php line 733
at Container->build(object(Closure), array()) in Container.php line 626
at Container->make('encrypter', array()) in Application.php line 674
at Application->make('Illuminate\Contracts\Encryption\Encrypter') in Container.php line 837
at Container->resolveClass(object(ReflectionParameter)) in Container.php line 800
at Container->getDependencies(array(object(ReflectionParameter)), array()) in Container.php line 771
at Container->build('SahraSalon\Http\Middleware\EncryptCookies', array()) in Container.php line 626
at Container->make('SahraSalon\Http\Middleware\EncryptCookies', array()) in Application.php line 674
at Application->make('SahraSalon\Http\Middleware\EncryptCookies') in Pipeline.php line 123
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 118
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 86
at Kernel->handle(object(Request)) in index.php line 54

Can anyone help solve this error?


Source: (StackOverflow)

Laravel 5 - Remove public from URL

I know this is a very popular question but I haven't been able to find a working solution for Laravel 5. I've been trying to migrate from Codeigniter for a long time, but this convoluted installation process keeps putting me off.

I don't want to run a VM, this just seems awkward when switching between projects.

I don't want to set my document root to the public folder, this is also awkward when switching between projects.

I've tried the .htaccess mod_rewrite method

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

This just gives me a Laravel NotFoundHttpException in compiled.php line 7610.

When I tried L4 a while ago, I used the method of moving the contents of the public folder into the root. The structure of L5 is quite different and following the same steps completely broke Laravel (the server would only return a blank page).

Is there a decent method of removing 'public' in a development environment that:

  1. Works with L5
  2. Allows me to switch between projects with ease (I'm usually working on 2 or 3 at any one time).

Thanks

** I'm using MAMP and PHP 5.6.2


Source: (StackOverflow)

Laravel is "listening" to index.php string anywhere in the URL

I have a Laravel 5 project with routes set up as well as a custom 404 page (mostly for missing/incorrect "pages").

So basically if I open any existing route I get the correct output and every other URL is showing the 404:

  • project.com/login - Fine, login page

  • project.com/ghdkfgl - 404

This looks clear and seems to be working as expected. So anything I add after the slash opens either an actual existing page or a 404 page.

Unless I put a 'index.php' anywhere in the URL. In this case, Laravel is executing the request for some reason like this:

  • project.com/jhdfkds/index.php/login - Opens the login page (the CSS and other resources are gone because of the paths but that's clear).

  • project.com/kfhjdsg/index.php/fkdhsg - Opens a 404 (but the CSS and other resources are not loaded too).

I'm sure both of these should open the 404 since there's no such routes in my project.

I also checked for the same behavior on the Laravel documentation website (I assume its built on Laravel).

What might be causing this? How can this be solved?

Why would Laravel even consider the 'index.php' in the middle of the URL?

Does this have anything to do with the .htaccess file? (I didn't edit it though)


Source: (StackOverflow)

How to structure a modular app in Laravel 5?

I would like to divide my application in modules. For instance, there would be a "core" modules that contains the basic login functionality, app layout/formatting (CSS etc), user management and a diary.

Later on I may create other modules like a contact manager that can easily be added or removed from the application.

There would be some logic in the apps navigation for determining which modules are present and to show/hide the links to them.

How can I do this in terms of directory structure, namespaces and anything else that's needed?


I am looking at creolab/laravel-modules but it states that it is for Laravel 4. Can I still use it with 5 in exactly the same way?

The documentation says to place models, controllers and views within each module directory, but how does this work with routes? Ideally I would like each module to have its own routes.php file. How will all of this work with the stuff in the http and the resources directory?


I was thinking of something like this:

Module idea

But I have no idea how I would get it to work.


I have just tried the tutorial here:

http://creolab.hr/2013/05/modules-in-laravel-4/

With no extra libraries etc, just pure Laravel 5.

I seem to have hit a brick wall with an error message:

FatalErrorException in ServiceProvider.php line 16:
Call to undefined method Illuminate\Config\Repository::package()

Regarding the following:

<?php namespace App\Modules;

abstract class ServiceProvider extends \Illuminate\Support\ServiceProvider
{

    public function boot()
    {
        if ($module = $this->getModule(func_get_args())) {
            $this->package('app/' . $module, $module, app_path() . '/modules/' . $module);
        }
    }

    public function register()
    {
        if ($module = $this->getModule(func_get_args())) {
            $this->app['config']->package('app/' . $module, app_path() . '/modules/' . $module . '/config');

// Add routes
            $routes = app_path() . '/modules/' . $module . '/routes.php';
            if (file_exists($routes)) require $routes;
        }
    }

    public function getModule($args)
    {
        $module = (isset($args[0]) and is_string($args[0])) ? $args[0] : null;

        return $module;
    }

}

What is causing this and how can I fix it?


Got my head around this a bit more now. Got my package/module routes and views working which is great:

abstract class ServiceProvider extends \Illuminate\Support\ServiceProvider
{

    public function boot()
    {
        if ($module = $this->getModule(func_get_args())) {
            include __DIR__.'/'.$module.'/routes.php';
        }
        $this->loadViewsFrom(__DIR__.'/'.$module.'/Views', 'core');
    }

    public function register()
    {
        if ($module = $this->getModule(func_get_args())) {

        }
    }

    public function getModule($args)
    {
        $module = (isset($args[0]) and is_string($args[0])) ? $args[0] : null;

        return $module;
    }

}

I have one last question, how would I load all my controllers from inside my package, much like how the loadViewsFrom() method works?


Source: (StackOverflow)