Thursday, 27 September 2018

Laravel Eloquent ORM get last insert id

In Laravel, when using the Eloquent ORM to insert a new record into the database, the inserted model instance will be updated with the auto-incrementing ID from the database. You can directly get the ID from the model instance without additional queries or commands.

How to Get the Last Insert ID with Laravel Eloquent

When you create a new record using Eloquent, Laravel automatically populates the model's ID property with the value of the newly inserted record's primary key. Here's a straightforward example:

$user = new User;
$user->name = "Tom";
$user->phone = "+154483480";
$user->save();

After the save method, use something like
$last_Insert_Id = $user->id;

In this snippet, $user->save() stores the new record in the database. Eloquent then automatically updates the $user object's id property with the ID of the newly inserted record.
 

Why is this feature important?

Obtaining the last inserted ID is crucial in many scenarios, such as redirecting users to a newly created resource, creating relationships between new and existing records, or logging activities. Laravel's Eloquent ORM makes this process seamless and efficient, enhancing the developer's productivity.

Using Custom Query Builder

We can get the last insert ID with the help of the query builder as well.
Here is a below snippet example.

$last_id = DB::table('products')->insertGetId(['id' => 22]);
 

Conclusion

Laravel's Eloquent ORM is a powerful tool that simplifies database interactions in PHP applications. Its ability to effortlessly provide the last inserted ID epitomizes the framework's goal: to simplify complex tasks and code more elegantly. Whether you're a seasoned Laravel developer or new to the framework, mastering Eloquent will significantly enhance your web development skills.
 

Wednesday, 8 August 2018

[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes



The error message is pretty straightforward: it indicates that an operation on a database table was halted because the size of the index being created exceeds the maximum allowed limit of 767 bytes. This limit is inherent to the InnoDB storage engine, which is the default for MySQL versions 5.6 and above. The error is most commonly encountered when working with VARCHAR or TEXT fields that are set to be unique or indexed, and the character set is utf8mb4, which allows for storing emojis and other multibyte characters.

Possible solutions :

Solution :

1) Go to the path in your Laravel installation


app/Providers/AppServiceProvider.php


or to see the default Laravel installation file AppServiceProvider.php
go here

https://github.com/laravel/laravel/blob/master/app/Providers/AppServiceProvider.php

In your file AppServiceProvider.php
 will see the method boot()






2) Simply update boot() method as like below:


use Illuminate\Support\Facades\Schema;


public function boot()
{
Schema::defaultStringLength(191); 

}  


5) Use a Different Character Set: 

If using utf8mb4 is not mandatory, switching to a character set that requires fewer bytes per character, like utf8, can also resolve the issue. However, this may not be suitable for all applications, especially those that need to store a wide variety of international characters.


3) Change the Database Engine:

    If altering the column length is not feasible or desirable, another approach is to switch to a database engine that supports larger index sizes. For MySQL, upgrading to version 5.7.7 or higher allows for the use of the innodb_large_prefix option, which increases the maximum index length to 3072 bytes.


  1. 4) Modify the Server Configuration:

  2. For those who cannot upgrade MySQL or change the engine, modifying the MySQL or MariaDB server configuration can provide a workaround. Setting the innodb_file_format to Barracuda and innodb_large_prefix to 1 in the server's my.cnf file can help overcome this limitation.

Thursday, 28 June 2018

Laravel Events Community


Laravel Events Community




Introducing the new Community know as Laravel Events. Where you will have
Events meetups and conferences.

The Laravel community is vibrant and active, with many events, conferences, meetups, and forums where developers gather to share knowledge, collaborate, and discuss the framework. If you're referring to "Laravel Events" in the context of community events and activities, here's a breakdown

Laracon: Laracon is the official Laravel conference. It usually happens once a year in the US and Europe (Laracon US and Laracon EU, respectively). Due to the pandemic, online versions like Laracon Online have also been hosted. It features talks from Taylor Otwell (Laravel's creator) and many other prominent community members.


Local Laravel Meetups: Many cities around the world have regular Laravel meetups where developers gather to discuss Laravel and related technologies. These are great places to network and learn from fellow developers.


Laracasts: While not an event, Laracasts is an invaluable resource for Laravel developers. Jeffrey Way offers numerous tutorials and series on Laravel and related web development topics.


Laravel News: This is a website and podcast that offers the latest news and updates about Laravel. They also feature interviews with community members and discuss the latest packages and tools.


Laravel Forums & Online Communities: There are active forums on the Laravel website where developers ask questions, share packages, and discuss best practices. In addition to this, the Laravel subreddit (r/laravel) and Laravel's Discord server are great places for real-time discussions.


Workshops & Training: From time to time, there are workshops and training sessions organized by community members or Laravel-focused companies to help developers dive deep into specific aspects of the framework.


Hackathons: Some events or gatherings might host Laravel-based hackathons, allowing developers to team up and create something in a limited timeframe.

If you're looking to engage with the community or learn from events, you should:Follow Laravel's official Twitter account and other prominent Laravel community members.
Join the Laravel subreddit and Discord server.
Look for local Laravel or PHP meetups on platforms like Meetup.com.
Regularly check the official Laravel website and Laravel News for announcements related to upcoming events or conferences.

Engaging with the community can significantly enhance your Laravel learning and development experience.


Link: https://laravelevents.com/

Wednesday, 27 June 2018

Laravel Auth facade

    Key Features of Laravel Auth Facade
Ease of Use: 

The Auth facade offers a straightforward syntax, allowing developers to quickly implement authentication features.

    Flexibility: 
    It supports various authentication drivers and stores, making it adaptable to different project requirements.
    Security: 
    Laravel's built-in features, such as password hashing and session management, enhance the security of your web applications.
After installing Authentication package we will have auth facade methods available.
Following are the list of useful authentication module methods.


Logout user from system use logout();
Auth::logout();
Code is used in the Laravel framework to log out the currently authenticated user. It clears the user's session information, effectively ending the user's authentication state. After this method is called, the user will no longer be considered logged in, and any subsequent attempts to access areas requiring authentication will redirect the user to the login page or prompt them to log in again.

Get Logged-In user data


Auth::user();
Get logged-In user id

$id = Auth::id();
The code retrieves the unique identifier (usually the primary key from the database) of the currently authenticated user using Laravel's authentication system. Auth::id() is a convenience method that returns the ID of the logged-in user without needing to load the entire user model. If no user is currently authenticated, it returns null. This is useful for quickly accessing the user's ID for database queries or logic that requires the user's ID.

Check if user is logged-In or not

if (Auth::check()) {
    
}
It checks if the current user is logged in using Laravel's authentication system. The Auth::check() method returns true if the user is authenticated, meaning there is a logged-in user session present. If the condition is true, the code inside the curly braces {} will be executed. This is typically used to conditionally display content or perform actions only for authenticated users.

Authenticate and remember user check

if (Auth::attempt(['email' => $email, 'password' => $password], $remember))
{
   
}
Above example for attempting to authenticate a user. It uses the Auth::attempt() method to check if the provided email and password match an existing user in the database. If the credentials are correct, the user is logged in. The $remember boolean indicates whether to remember the user's session so they don't need to log in again on their next visit. If the authentication is successful, the code within the braces {} will be executed.

We can also protect routes of our application.

For example:

Route::get('profile', ['middleware' => 'auth', function()
{
  
}]);
Route::get('products', ['middleware' => 'auth', function()
{
    
}]);
Route::get('categories', ['middleware' => 'auth', function()
{
    
}]);

For further details and information please see the official docs

Laravel Auth package/module installation and configuration


Usually, in all other MVC frameworks, we do not have an authentication module or any package available. But luckily laravel offer authentication functionality of the package. Which save allot of time
and it is quite useful to use.

Step 1: Install Laravel

Before you dive into the installation of the Laravel Auth package, ensure you have Laravel installed on your system. If not, you can install it by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel yourProjectName

Step 2: Install Laravel UI

Laravel UI is a separate package that provides the UI essentials for your authentication system. Install it using Composer with the following command:

composer require laravel/ui

Step 3: Generate Auth Scaffolding


Once Laravel UI is installed, you can easily generate the auth scaffolding by running one of the following commands, depending on your preference for the front-end:

For Bootstrap 
php artisan ui bootstrap --auth

Step 4: Migrate the Database


php artisan migrate 


After running the migration all database tables will get created. Moreover all login, register
routes will be available for use


Navigate your browser to
 http://website.com/register
 http://website.com/login


For further details see  Auth Facade


Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...