#laravel#helper

The abort function throws back a specified HTTP exception.

abort(404);
copy
#laravel#helper

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

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

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

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

Auth helper functions.

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
#laravel#auth

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

// 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
#laravel#helper

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

return back();
copy
#laravel#model

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.

// 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
#laravel#route#cache

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.

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
#laravel#view

Compact function allows you to pass data to the view.

$color = 'blue';
$shape = 'square';

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

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

$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
#laravel

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

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

Cross-Site Request Forgery token.

{{ csrf_field() }}

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

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

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

Helpful debugging function.

dd($some-data);
copy
#laravel#helper

A helper function for raising events.

event(new ItemWasAdded($item));
copy
#laravel#db#factory

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.

factory('App\Item')->create()

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

Faker function lets you generate dummy data for seeding the database. Read more at www.github.com/fzaninotto/Faker

$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
#laravel

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.

findOrFail();

// Use case
Item::findOrFail($item);
copy
#laravel#db#migration

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

// 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
#laravel#model

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.

// 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
#laravel

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.

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
#laravel

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

laravel new your-project-name
copy
#laravel#log

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.

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

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

{{ method_field('PATCH') }}

// This returns
<input type="hidden" name="_method" value="PATCH">
copy
#laravel#route#view

Examples of passing data to a 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
#laravel#eloquent#db

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

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

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

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

Protected method allows to set fillable or guarded fields in the 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
#laravel#collection

Revert items order in the collection.

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

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

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

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.

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

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

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
#laravel#migration#db

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

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

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

// 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
Sitemap Git repository