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.
There are a few ways to apply the auth middleware in your project.
#laravel#auth
// In the Controller constructor...publicfunction__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 routesRoute::get('item','ItemsController@index')->middleware('auth');
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 fileclassSubItemextendsModel{publicfunctionitem(){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;
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.
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.
// 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() );
// }
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 requestfactory('App\Item',10)->create()
$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
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.
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 examplepublicfunctionup(){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')});}
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 fileclassItemextendsModel{publicfunctionsubitems(){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;
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
returnDB::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();
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.
Route::get('/',function(){// Data example$sections=['Intro','Information','Stats'];// OPTION 1 - Pass in the second argument.returnview('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.returnview('dashboard')->withSections($sections)->withData($data);// OPTION 3 - Combining the two approaches above.returnview('dashboard')->with(['sections'=>['Intro','Information','Stats'],'data'=>'Some other data']);});
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.
This command will install only the production dependencies from your composer.json file. This is typically used when deploying application to production environments.
Protected method allows to set fillable or guarded fields in the model.
#laravel#model
classItemextendsModel{protected$fillable=['title','content'// Only changes to these fields ARE allowed.];}classOtherItemextendsModel{protected$guarded=['id','date'// Changes to these fields ARE NOT allowed.];}
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 parameterroute('shop',$product->slug)// Or an array of parametersroute('shop',['product'=>$product->slug,'title'=>$product->name])
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}
*/