The abort function throws back a specified HTTP exception.

#laravel#helper
abort(404);
copy

The abort if function throws back a specified HTTP exception if the first attribute evaluates to true.

#laravel#helper
abort_if(! auth()->check(), 403, "Unauthorized");
copy

The abort unless function throws back a specified HTTP exception if the first attribute evaluates to false.

#laravel#helper
abort_if(auth()->id(), 403, "Unauthorized");
copy

Auth helper functions.

#laravel#auth
auth()->id()    // Returns null if the user is not logged in or a User id if they are.
auth()->user()  // Returns a User instance.
auth()->check() // Returns boolean: true for logged in.
auth()->guest() // Returns boolean: true for a guest user.
 
copy

There are a few ways to apply the auth middleware in your project.

#laravel#auth
// In the Controller constructor
...
    public function __constructor(){
        $this->middleware('auth') // Apply login authorization to all functions
        // or
        $this->middleware('auth')->only(['store', 'update']) // Apply login authorization only to the given functions
        // or
        $this->middleware('auth')->except(['show']) // Apply login authorization to all except the given functions
    }
...

// In the routes file you can apply Auth Middleware to specific routes
Route::get('item', 'ItemsController@index')->middleware('auth');
 
copy

Returning back function will redirect the user to the previous step.

#laravel#helper
return back();
copy

Belongs to sets a single-to-single relationship between two Models. Use it for fetching a parent Model associated with your class. Pass a Model class you want to reference as an argument.

#laravel#model
// Set the relationship in a Model file

class SubItem extends Model {
    public function item() {
        return $this->belongsTo(Item::class); // SubItem belongs to an Item
    }
}

// Then, in a Controller, you can fetch the Item your Model belongs to.  
App\SubItem::first()->item;
copy

In some cases you might need to clear Laravel's cache without using console. You can set up the following route and run Artisan cache clear command as a call-back function instead. In addition, follow it up with Artisan config cache command to rebuild application cache again. Then, visit the new route in your browser to trigger the Artisan commands.

#laravel#route#cache
Route::get('/clear-cache', function() {

    $clearCache = Artisan::call('cache:clear');
    echo "Cache cleared. \r\n";

    $setCache = Artisan::call('config:cache');
    echo "Cache configured. \r\n";
});
copy

Compact function allows you to pass data to the view.

#laravel#view
$color = 'blue';
$shape = 'square';

view('geometry',compact("color","shape")); 
copy

Returns the configuration record value using the dot notation. Second argument lets you pass an optional default value.

#laravel#helper
$appname = config('app.name', 'Default name');
// Go to the /config folder, look into the app.php file and get me the value of the 'name' record if it exists.
copy

Create method lets you set and persist a new item in one simple command.

#laravel
Item::create([
    'title' => 'New item',
    'data' => 'More data'
]);
copy

Cross-Site Request Forgery token.

#laravel#blade
{{ csrf_field() }}

// This returns
<input type="hidden" name="_token" value="[CSRF_HASH_TOKEN]">
copy

Set a default value of the record in the Migration class.

#laravel#migration#db
$table->boolean('allowed')->default(0);
 
copy

Helpful debugging function.

#laravel
dd($some-data);
copy

Add the following code to AppService provider within the boot() method. It will help with catching common errors in your production environment.

#laravel#log#debug
// public function boot()

// {

    Model::shouldBeStrict( !$this->app->isProduction() )
    
    // shouldBeStrict runs the following methods in the background

    // Model::preventLazyLoading( !$this->app->isProduction() );

    // Model::preventSilentlyDiscardingAttributes( !$this->app->isProduction() );

    // Model::preventAccessingMissingAttributes( !$this->app->isProduction() );

// }
copy

A helper function for raising events.

#laravel#helper
event(new ItemWasAdded($item));
copy

Run Factory class in tinker to quickly generate database records. You can create multiple records in one go by passing a number of records to create as the second factory argument.

#laravel#db#factory
factory('App\Item')->create()

// Create multiple records in one request
factory('App\Item', 10)->create()
copy

Faker function lets you generate dummy data for seeding the database.

#laravel#db
$faker = Faker\Factory::create();

$faker->name; // First and second name
$faker->randomDigit; // A random number
$faker->word; // A single word
$faker->sentence; // A sentence
$faker->unique()->word; // A single unique word
$faker->text($maxNbChars = 300); // 300 character long text
$faker->safeEmail; // An email address
$faker->hexcolor; // Hex color
copy

Find or fail method provides support for requests that fail to return any data from the data base. Rather than letting the app crash it captures the error and displays an in-built, user-friendly message.

#laravel
findOrFail();

// Use case
Item::findOrFail($item);
copy

Set a foreign key in the data base table. Makes a reference between tables using an id and a foreign key.

#laravel#db#migration
// Migration example
public function up(){
    Schema::create('subitems', function (Blueprint $table) {
        // Create all table fields
        $table->increments('id');
        $table->unsignedInteger('item_id');
        $table->string('text');
        $table->timestamps();
        
        // Set the foreign key
        $table->foreign('item_id')->references('id')->on('items');
        // Append the function below if you want to automatically remove all Subitems related to the Item
        // onDelete('cascade')
    });
}
copy

Has many sets a single-to-many relationship between two Models. Use plural form in the name of your function (subitems in this example). This is a good practice as a collection of records will be returned when the method is called. Pass a Model class you want to reference as an argument.

#laravel#model
// Set the relationship in a Model file

class Item extends Model {
    public function subitems() {
        return $this->hasMany(SubItem::class); // Item has many SubItems
    }
}

// Then, in a Controller, you can fetch all SubItems related to the Item like so 
App\Item::first()->subitems;
copy

Example of joining to collections using join function helper. First argument determines a table to join, the two following arguments select columns to make the join at.

#laravel
return DB::table('users')
->join('messages', 'messages.from', 'users.id') // Select table to join and keys to make a join at
->select('from', 'name', 'text', 'messages.created_at' )
->get();
copy

Navigate to the directory you want to start the new Laravel project and run the following command.

#laravel
laravel new your-project-name
copy

Submit a log message to configured channels. There is eight types of messages to choose from, alert, emergency, error, critical, debug, info, notice and warning. Debug type has been used in the code example.

#laravel#log
Log::debug($application-log);
copy

Method field in Laravel provides the missing support for the requests like PATCH and DELETE.

#laravel#blade
{{ method_field('PATCH') }}

// This returns
<input type="hidden" name="_method" value="PATCH">
copy

Examples of passing data to a view.

#laravel#route#view
Route::get('/', function(){
    
    // Data example
    $sections = ['Intro','Information','Stats'];

    // OPTION 1 - Pass in the second argument.
    return view('dashboard', [
        'sections' => $sections // This variable is now available in the dashboard view
        'data' => 'Some other data' // You can create multiple data holding data
    ]);

    // OPTION 2 - Using "with" magic methods.
    return view('dashboard')->withSections($sections)->withData($data);

    // OPTION 3 - Combining the two approaches above.
    return view('dashboard')->with([
        'sections' => ['Intro','Information','Stats'],
        'data' => 'Some other data'
    ]);
});
copy

Pluck is an eloquent helper function for narrowing down your database queries and returning a collection of specific columns.

#laravel#eloquent#db
$item->getAllSubitems->pluck('title');
copy

Add the following code to AppService provider within the boot() method. This is to flag an issue when Laravel is trying to make unnecessary calls to the database. The passed attribute evaluates to a boolean and ensures the debug message doesn't display in the production environment.

#laravel#log#debug
Model::preventLazyLoading( !$this->app->isProduction() );
copy

This command will install only the production dependencies from your composer.json file. This is typically used when deploying application to production environments.

#laravel#composer
composer install --no-dev
copy

Protected method allows to set fillable or guarded fields in the model.

#laravel#model
class Item extends Model {
    protected $fillable = [
        'title', 'content' // Only changes to these fields ARE allowed.
    ];
}

class OtherItem extends Model {
    protected $guarded = [
        'id', 'date' // Changes to these fields ARE NOT allowed.
    ];
}
copy

Revert items order in the collection.

#laravel#collection
$reversedItems = $items->reverse();
copy

Basic route example returning a view. Routes are located in the /routes folder of your application.

#laravel#route#view
Route::get('/', function(){
    return view('dashboard');
});
copy

Use route helper to return a full url to a named route. You can pass parameters in the second argument for the dynamic parts of the url.

#laravel#helper
route('home')
// With a single parameter
route('shop', $product->slug)
// Or an array of parameters
route('shop', ['product' => $product->slug, 'title' => $product->name])
copy

Using resource method will create a complete list of routes required for listing, creating, storing, editing and removing items.

#laravel#route
Route::resource('items', 'ItemsController'); // this will generate all the routes listed below

/*
    
    // DISPLAY
        GET     /items                      ItemsController@index       Show all Items
        GET     /items/{itemID}             ItemsController@show        Show a single Item with an id of {itemsID}

    // CREATE
        GET     /items/create               ItemsController@create      Show form to create a new Item
        POST    /items                      ItemsController@store       Add new Item

    // EDIT
        GET     /items/{itemID}/edit        ItemsController@edit        Show form to edit an existing Item with an id of {itemID}
        PATCH   /items/{itemID}             ItemsController@update      Update an exiting Item with an id of {itemID}

    // REMOVE
        DELETE  /items/{itemID}             ItemsController@destroy     Delete project with an id of {itemID}

*/
copy

Unique function protects database from holding multiple records with the same value.

#laravel#migration#db
// Inside of a migration
$table->string('category')->unique(); // Only one category of each type will be crated.
copy

Validate function allows you to set rules for the data passed in the request. If the validation fails Laravel returns an Errors object.

#laravel#controller#data
// Controller file
public function store() {
    request()->validate([
        'FirstName' => 'required',
        'SecondName' => 'required'
    ]);
}

// View file
@if ($errors->any())
    @foreach ($errors->all() as $error)
        {{ $error }}
    @endforeach
@endif
copy