DEV Community

Cover image for 11 Most Asked Questions About Laravel
KiranPoudel98 for Truemark Technology

Posted on • Originally published at thedevpost.com

11 Most Asked Questions About Laravel

Laravel is a free open-source PHP framework that helps to develop web apps easily. There are several PHP frameworks but among them, Laravel is the most popular one. Being the popular one, users have many questions. So, today we will be talking about the most asked questions about Laravel.

11 Most Asked Questions About Laravel

1. What are the best practices for custom helpers in Laravel 5?

Answer:

Create a helpers.php file in your app folder and load it up with composer:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php" // <---- ADD THIS
    ]
},
Enter fullscreen mode Exit fullscreen mode

After adding that to your composer.json file, run the following command:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

If you don’t like keeping your helpers.php file in your app directory (because it’s not a PSR-4 namespaced class file), you can do what the laravel.com website does: store the helpers.php in the bootstrap directory. Remember to set it in your composer.json file:

"files": [
    "bootstrap/helpers.php"
]
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

This answer is applicable to general custom classes within Laravel.

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create an alias:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...
Enter fullscreen mode Exit fullscreen mode

Step 3: Run composer dump-autoload in the project root

Step 4: Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}
Enter fullscreen mode Exit fullscreen mode

Extra Credit: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...
Enter fullscreen mode Exit fullscreen mode

Source: http://www.php-fig.org/psr/psr-4/

Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php

2. How to fix error “Laravel requires the Mcrypt PHP extension”?

Answer:

The web-enabled extensions and command-line enabled extensions can differ. Run php -m in your terminal and check to see if mcrypt is listed. If it does not then check where the command line is loading your php.ini file from by running php --ini from your terminal.

In this php.ini file you can enable the extension.

OSX

Many people on OSX run into problems due to the terminal pointing to the native PHP shipped with OSX. You should instead update your bash profile to include the actual path to your PHP. Something like this:

export PATH=/usr/local/php5/bin:$PATH
Enter fullscreen mode Exit fullscreen mode

Ubuntu

On earlier versions of Ubuntu (prior to 14.04) when you run sudo apt-get install php5-mcrypt it doesn’t actually install the extension into the mods-available. You’ll need to symlink it.

sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini
Enter fullscreen mode Exit fullscreen mode

On all Ubuntu versions you’ll need to enable the mod once it’s installed. You can do that with php5enmod.

sudo php5enmod mcrypt
sudo service apache2 restart
Enter fullscreen mode Exit fullscreen mode

NOTES

3. How to create multiple where clause query using Laravel Eloquent?

Answer:

In Laravel 5.3 (and still true as of 6.x) you can use more granular wheres passed as an array:

$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])
Enter fullscreen mode Exit fullscreen mode

Personally we haven’t found use-case for this over just multiple where calls, but fact is you can use it.

Since June 2014 you can pass an array to where

As long as you want all the wheres use and operator, you can group them this way:

$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];

// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
Enter fullscreen mode Exit fullscreen mode

Then:

$results = User::where($matchThese)->get();

// with another group
$results = User::where($matchThese)
    ->orWhere($orThose)
    ->get();
Enter fullscreen mode Exit fullscreen mode

The above will result in such query:

SELECT * FROM users
  WHERE (field = value AND another_field = another_value AND ...)
  OR (yet_another_field = yet_another_value AND ...)
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

Query scopes can help you to let your code more readable.

http://laravel.com/docs/eloquent#query-scopes

In your model, create scopes methods like this:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}
Enter fullscreen mode Exit fullscreen mode

Then, you can call this scopes while building your query:

$users = User::active()->that()->get();
Enter fullscreen mode Exit fullscreen mode

4. How to get the last inserted id using Laravel Eloquent?

Answer:

For updated Laravel version try this:

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

For those who might be using DB::statement or DB::insert, there is another way:

DB::getPdo()->lastInsertId();
Enter fullscreen mode Exit fullscreen mode

5. How to display HTML with Blade in Laravel 5?

Answer:

You need to use

{!! $text !!}
Enter fullscreen mode Exit fullscreen mode

The string will auto escape when using {{ $text }}.

Alternative Answer:

For Laravel 5

{!!html_entity_decode($text)!!}
Enter fullscreen mode Exit fullscreen mode

6. How to say WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)?

Answer:

Make use of Parameter Grouping (Laravel 4.2). For example:

Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

If you want to use parameters for a,b,c,d in Laravel 4

Model::where(function ($query) use ($a,$b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});
Enter fullscreen mode Exit fullscreen mode

7. Is there a way to check whether an Eloquent collection returned from $result = Model::where(...)->get() is empty, as well as counting the number of elements?

Answer:

When using ->get() you cannot simply use any of the below:

if (empty($result)) { }
if (!$result) { }
if ($result) { }
Enter fullscreen mode Exit fullscreen mode

Because if you dd($result); you’ll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you’re checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
Enter fullscreen mode Exit fullscreen mode

You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.

$result = Model::where(...)->first();
if ($result) { ... }
Enter fullscreen mode Exit fullscreen mode

Bonus Information

The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason, it can be confusing to know what one you’re working on.

The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you’re not sure what class you’re actually working with, try doing var_dump(User::all()) and experimenting to see what classes it’s actually returning (with help of get_class(...)).

We highly recommend you check out the source code for the Collection class, it’s pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.

8. How to add a new column to existing table in a migration?

Answer:

To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

For Laravel 3:

php artisan migrate:make add_paid_to_users
Enter fullscreen mode Exit fullscreen mode

For Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users
Enter fullscreen mode Exit fullscreen mode

You then need to use the Schema::table() method (as you’re accessing an existing table, not creating a new one). And you can add a column like this:

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}
Enter fullscreen mode Exit fullscreen mode

and don’t forget to add the rollback option:

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}
Enter fullscreen mode Exit fullscreen mode

Then you can run your migrations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

This is all well covered in the documentation for both Laravel 3:

And for Laravel 4 / Laravel 5:

Also,

use $table->integer('paid')->after('whichever_column'); to add this field after a specific column.
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

To make things quicker, you can use the flag “–table” like this:

php artisan make:migration add_paid_to_users --table="users"
Enter fullscreen mode Exit fullscreen mode

This will add the up and down method content automatically:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        //
    });
}
Enter fullscreen mode Exit fullscreen mode

Similarly, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations.

9. How to get the current URL inside @if statement (Blade) in Laravel 4?

Answer:

You can use: Request::url() to obtain the current URL, here is an example:

@if(Request::url() === 'your url here')
    // code
@endif
Enter fullscreen mode Exit fullscreen mode

Laravel offers a method to find out, whether the URL matches a pattern or not

if (Request::is('admin/*'))
{
    // code
}
Enter fullscreen mode Exit fullscreen mode

Check the related documentation to obtain different request information: http://laravel.com/docs/requests#request-information

Alternative Answer:

You can also use Route::current()->getName() to check your route name.

Example: routes.php

Route::get('test', ['as'=>'testing', function() {
    return View::make('test');
}]);
Enter fullscreen mode Exit fullscreen mode

View:

@if(Route::current()->getName() == 'testing')
    Hello This is testing
@endif
Enter fullscreen mode Exit fullscreen mode

10.. What to do to see if $user has a record?

Answer:

It depends if you want to work with the user afterward or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}
Enter fullscreen mode Exit fullscreen mode

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}
Enter fullscreen mode Exit fullscreen mode

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}
Enter fullscreen mode Exit fullscreen mode

Alternative Answer:

One of the best solutions is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.

11. How to fix error “Allowed memory size of 536870912 bytes exhausted” in Laravel?

Answer:

You can try editing /etc/php5/fpm/php.ini:

; Old Limit
; memory_limit = 512M

; New Limit
memory_limit = 2048M
Enter fullscreen mode Exit fullscreen mode

You may need to restart Nginx.

Alternative Answer:

The solution is to change memory_limit in php.ini but it should be the correct one. So you need one responsible for the server, located there:

/etc/php/7.0/cli/php.ini
Enter fullscreen mode Exit fullscreen mode

so you need a line with

memory_limit
Enter fullscreen mode Exit fullscreen mode

After that, you need to restart PHP service

sudo service php7.0-fpm restart
Enter fullscreen mode Exit fullscreen mode

to check if it was changed successfully you need to use the command line to run this:

php -i
Enter fullscreen mode Exit fullscreen mode

the report contained following line

memory_limit => 2048M => 2048M
Enter fullscreen mode Exit fullscreen mode

Now test cases are fine.

In Conclusion

These are the 11 most asked questions about the Laravel. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you.

We, at Truemark, provide services like web and mobile app development, digital marketing, and website development. So, if you need any help and want to work with us, please feel free to contact us.

Hope this article helped you.

This post was first published on DevPostbyTruemark.

Top comments (0)