Index
forelse
Arrays
String Helper
If-ELSE OR TERNARY CONDITION
Use json_decode() and json_encode()
Blade directives to avoid null condition
Validation Rules
Avoid Null value while saving or updating data
Use Exception handling to avoid error-prone code
to best performance store data in json format in phpmyadmin
Perform more functionality through less coding
Data processing task and bussiness logic use in controller side
Avoid duplicate record from tables
Best Practice: Use the @forelse directive instead of foreach for iterating through data and handling empty cases.
forelse
<ul>
@forelse($items as $item)
<li>{{ $item }}</li>
@empty
<li>No items found</li>
@endforelse
</ul>
Arrays
:
Best Practice: Leverage Laravel's collection methods for working with arrays.
$items = Item::all(); or $items = Item::get()
$filteredItems = $items->filter(function ($item) {
return $item->price > 50;
});
// Example: Transform the items
$transformedItems = $filteredItems ->map(function ($item) {
return [
'name' => $item->name,
'formatted_price' => '$' . number_format($item->price, 2),
];
});
$items = Item::all();
$transformedItems = $items->map(function ($item) {
return [
'name' => $item->name,
'formatted_price' => '$' . number_format($item->price, 2),
];
});
String Helper
Use Str::slug for Generating Slugs:
Best Practice: Generate URL-friendly slugs from strings.
Example:
use Illuminate\Support\Str;
$title = "Laravel Best Practices";
$slug = Str::slug($title);
Use Str::limit for Truncating Strings:
Best Practice: Limit the length of a string and add an ellipsis if needed.
Example:
use Illuminate\Support\Str;
$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$shortContent = Str::limit($content, 50);
Use Str::random for Generating Random Strings:
Best Practice: Generate random strings for various purposes.
Example:
use Illuminate\Support\Str;
$randomString = Str::random(10);
Use Str::startsWith and Str::endsWith for Checking Prefix and Suffix:
Best Practice: Check if a string starts or ends with a specific substring.
Example:
use Illuminate\Support\Str;
$text = "Laravel is awesome";
$startsWithLaravel = Str::startsWith($text, 'Laravel');
$endsWithAwesome = Str::endsWith($text, 'awesome');
Use Str::contains for Checking Substring Presence:
Best Practice: Check if a string contains a specific substring.
Example:
use Illuminate\Support\Str;
$text = "Laravel is awesome";
$containsAwesome = Str::contains($text, 'awesome');
Use Str::camel and Str::snake for Converting Case:
Best Practice: Convert strings between camel case and snake case.
Example:
use Illuminate\Support\Str;
$camelCase = Str::camel('laravel_best_practices');
$snakeCase = Str::snake('LaravelBestPractices');
Use Str::plural and Str::singular for Handling Pluralization:
Best Practice: Handle pluralization and singularization of words.
Example:
use Illuminate\Support\Str;
$plural = Str::plural('apple');
$singular = Str::singular('apples');
Use Str::title for Converting to Title Case:
Best Practice: Convert a string to title case.
use Illuminate\Support\Str;
$titleCase = Str::title('laravel best practices');
Use Str::ucfirst and Str::lcfirst for Case Manipulation:
Best Practice: Manipulate the first letter of a string.
use Illuminate\Support\Str;
$ucfirst = Str::ucfirst('laravel');
$lcfirst = Str::lcfirst('Laravel');
Use Str::replaceFirst and Str::replaceLast for Replacing First/Last Occurrence:
Best Practice: Replace the first or last occurrence of a substring.
Example:
use Illuminate\Support\Str;
$text = "laravel is awesome and laravel is powerful";
$replaceFirst = Str::replaceFirst('laravel', 'Laravel', $text);
$replaceLast = Str::replaceLast('laravel', 'Laravel', $text);
By following these best practices and using the Str class methods, you can perform various string manipulations efficiently and consistently in your Laravel applications.
If-ELSE OR TERNARY CONDITION
If-ELSE
Best Practice: Keep your code readable by using ternary operators for concise conditions.
When retrieving dynamic data from a database in Laravel, using if-else conditions can make your code more readable. Here's a checklist with examples:
Use if-else for Retrieving a Single Model with first:
Best Practice: Use if-else conditions for clarity when retrieving a single model with first.
$user = User::where('id', $userId)->first();
if ($user) {
$name = $user->name;
} else {
$name = 'Default Name';
}
Use if-else for Retrieving a Collection with get:
Best Practice: Use if-else conditions for readability when retrieving a collection with get.
$users = User::where('status', 'active')->get();
if ($users->isEmpty()) {
$activeUsers = [];
} else {
$activeUsers = $users;
}
Use if-else for Transformation with map:
Best Practice: Use if-else conditions for readability when applying transformations with map.
$items = Item::all();
$transformedItems = $items->map(function ($item) {
$status = $item->status == 'active' ? 'Active' : 'Inactive';
return [
'name' => $item->name,
'status' => $status,
];
});
Use if for Null Checking:
Best Practice: Use if conditions for null checking and handle accordingly.
$user = User::find($userId);
if ($user) {
$email = $user->email;
} else {
$email = 'No Email Available';
}
Combine if with Null Coalescing Operator (??):
Best Practice: Combine if conditions with the null coalescing operator for concise default values.
$user = User::find($userId);
if ($user) {
$displayName = $user->display_name ?? $user->name;
} else {
$displayName = 'Guest';
}
Use if-else for Dynamic Value Selection:
Best Practice: Use if-else conditions for dynamic value selection based on conditions.
$isAdmin = true;
if ($isAdmin) {
$role = 'Administrator';
} else {
$role = 'User';
}
Avoid Deeply Nested if-else for Readability:
Best Practice: Avoid deeply nested if-else conditions for better readability.
if ($user->is_active == 1) {
$status = 'Active';
} elseif ($user->is_pending == 1) {
$status = 'Pending';
} else {
$status = 'Inactive';
}
Use if-else for Conditional Array Assignment:
Best Practice: Use if-else conditions for concise array assignment based on conditions.
$status = $user->is_active
? ['class' => 'active', 'text' => 'Active']
: ['class' => 'inactive', 'text' => 'Inactive'];
By applying these practices, you can make your code more readable and maintainable when dealing with dynamic data retrieval in Laravel. Always aim for clarity and readability to enhance the maintainability of your code.
TERNARY CONDITION
Using ternary operators for concise conditions can help keep your code readable and concise when retrieving dynamic data from the database in Laravel. Here's a checklist with examples:
Use Ternary Operator for Retrieving a Single Model with first:
Best Practice: Use a ternary operator for concise conditions when retrieving a single model with first.
$user = User::where('id', $userId)->first();
$name = $user ? $user->name : 'Default Name';
Use Ternary Operator for Retrieving a Collection with get:
Best Practice: Use a ternary operator for concise conditions when retrieving a collection with get.
$users = User::where('status', 'active')->get();
$activeUsers = $users->isEmpty() ? [] : $users;
Use Ternary Operator with map for Transformation:
Best Practice: Use a ternary operator with map for concise transformation conditions.
$items = Item::all();
$transformedItems = $items->map(function ($item) {
return [
'name' => $item->name,
'status' => $item->status == 'active' ? 'Active' : 'Inactive',
];
});
Use Null Coalescing Operator (??) for Default Values:
Best Practice: Use the null coalescing operator for concise default value conditions.
$user = User::find($userId);
$email = $user->email ?? 'No Email Available';
Combine Ternary Operator and Null Coalescing Operator:
Best Practice: Combine the ternary operator and null coalescing operator for concise and readable conditions.
$user = User::find($userId);
$displayName = $user ? ($user->display_name ?? $user->name) : 'Guest';
Use Ternary Operator for Dynamic Value Selection:
Best Practice: Use ternary operators for dynamic value selection based on conditions.
$isAdmin = true;
$role = $isAdmin ? 'Administrator' : 'User';
Avoid Nested Ternary Operators for Readability:
Best Practice: Avoid deeply nested ternary operators for better readability.
$status = ($user->is_active == 1) ? 'Active' : (($user->is_pending == 1) ? 'Pending' : 'Inactive');
Use Ternary Operator for Conditional Array Assignment:
Best Practice: Use ternary operators for concise array assignment based on conditions.
$status = $user->is_active ? ['class' => 'active', 'text' => 'Active'] : ['class' => 'inactive', 'text' => 'Inactive'];
By applying these practices, you can maintain readability while making your code concise and expressive when dealing with dynamic data retrieval in Laravel. Always prioritize readability, and avoid overly complex ternary conditions for better code maintainability.
Blade directives to avoid null condition
@if($condition)
@if($condition)
// Display something
@else
// Display something else
@endif
Using isset() for Checking Variable Existence
if (isset($variable)) {
// Do something with $variable
}
Using filled() Helper:
if (filled($variable)) {
// Do something with $variable
}
Use json_decode() and json_encode()
Use json_encode() for Converting PHP Array to JSON:
Best Practice: Convert a PHP array to a JSON string using json_encode().
to best performance of query store data in json format
when u request data comes after submit form
<form method="POST" action="{{ route('processForm') }}">
@csrf
<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<!-- Additional data -->
<label for="age">Age:</label>
<input type="number" name="age" id="age" required>
<button type="submit">Submit</button>
</form>
$data = ['name' => 'John', 'age' => 25];
$jsonData = json_encode($data);
Use json_decode() for Converting JSON to PHP Array:
Best Practice: Convert a JSON string to a PHP array using json_decode().
$items = Item::all(); or $items = Item::get()
$jsonData = '{"name":"John","age":25}';
$data = json_decode($jsonData, true);
Use json_encode() for Storing JSON in Database:
Best Practice: Use json_encode() when storing JSON data in a database field.
$data = ['key' => 'value'];
$jsonData = json_encode($data);
// Store $jsonData in the database
Use json_decode() for Retrieving JSON from Database:
Best Practice: Use json_decode() when retrieving JSON data from a database field.
// Retrieve $jsonData from the database
$data = json_decode($jsonData, true);
Handle Errors with json_last_error() and json_last_error_msg():
Best Practice: Check for errors when working with JSON encoding and decoding.
$data = json_decode($jsonData);
if (json_last_error() === JSON_ERROR_NONE) {
// JSON decoding successful
} else {
// Handle JSON decoding error
$errorMessage = json_last_error_msg();
}
Use Options Parameter with json_decode() for Custom Behavior:
Best Practice: Utilize the options parameter for custom behavior with json_decode().
$jsonData = '{"name":"John","age":25}';
$data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);
Use json_encode() with Options for Formatting:
Best Practice: Use the options parameter for formatting JSON output.
$data = ['name' => 'John', 'age' => 25];
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
use json_decode while filtring
$filteredDatas = [];
foreach ($data as $profile) {
$profileStatus = json_decode($profile->profile_status, true);
if (isset($profileStatus['price']) && $profileStatus['price'] == 'yes') {
$filteredDatas[] = $profile;
}
}
Consider Using Eloquent Mutators for Database Fields:
Best Practice: When working with Laravel Eloquent models, consider using mutators for automatic encoding/decoding.
class User extends Model
{
public function setDataAttribute($value)
{
$this->attributes['data'] = json_encode($value);
}
public function getDataAttribute($value)
{
return json_decode($value, true);
}
}
Handle JSON-Encoded Form Input in Laravel Requests:
Best Practice: When dealing with JSON-encoded form input, use json_decode() in Laravel requests.
$jsonData = $request->input('json_data');
$data = json_decode($jsonData, true);
Validation Rules
$request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
'published_at' => 'nullable|date',
]);
Avoid Null value while saving or updating data
When using the ternary operator in conjunction with $model->save() for updating data in Laravel, you can follow these best practices to avoid saving null values:
Use Ternary Operator for Field Assignment:
Best Practice: Use the ternary operator to conditionally assign values before calling $model->save().
Example:
// Assuming $post is an existing instance of the Post model
$post->title = $request->input('title') ?: $post->title;
$post->content = $request->input('content') ?: $post->content;
$post->published_at = $request->input('published_at') ?: $post->published_at;
$post->save();
In this example, the ternary operator is used to check if the request contains a value for each field. If a value is present, it is assigned; otherwise, the existing value is used.
Consider Using filled Helper:
Best Practice: Utilize Laravel's filled helper to check if a request input is not null or an empty string before assigning it.
Example:
$post->title = filled($request->input('title')) ? $request->input('title') : $post->title;
$post->content = filled($request->input('content')) ? $request->input('content') : $post->content;
$post->published_at = filled($request->input('published_at')) ? $request->input('published_at') : $post->published_at;
$post->save();
Practical Example
public function addProfileWithSlug(Request $request)
{
$input = $request->all();
$getting_id = Auth::user()->id;
log::info('user id me kya aa rha hai 67d.' . $getting_id);
$adding_profile = Addprofile::where('user_id', $getting_id)->first();
$fb = $request->facebook !== null ? $request->facebook :($adding_profile ?$add_face : null);
log::info($fb);
$twitter = $request->twitter !== null ? $request->twitter :($adding_profile ?$add_twitter : null);
$youtube = $request->youtube !== null ? $request->youtube : ($adding_profile ?$add_youtube : null);
$wordpress =$request->wordpress !== null ? $request->wordpress : ($adding_profile ?$add_wordpress : null);
$tumblr =$request->tumblr !== null ? $request->tumblr :($adding_profile ?$add_tumblr : null);
$instagram = $request->instagram !== null ? $request->instagram :($adding_profile ?$add_instagram : null);
$quora =$request->quora !== null ? $request->quora :($adding_profile ?$add_quora : null);
$pinterest = $request->pinterest !== null ? $request->pinterest :($adding_profile ?$add_pinterest : null);
$reddit = $request->reddit !== null ? $request->reddit : ($adding_profile ?$add_reddit : null);
$scoopit =$request->scoopit !== null ? $request->scoopit : ($adding_profile ?$add_scoopit : null);
$slashdot = $request->slashdot !== null ? $request->slashdot : ($adding_profile ?$add_slashdot : null);
$telegram = $request->telegram !== null ? $request->telegram : ($adding_profile ?$add_telegram : null);
$fb_grp = $request->fb_grp !== null ? $request->fb_grp : ($adding_profile ?$add_fb_grp : null);
$linkedin_grp = $request->linkedin_grp !== null ? $request->linkedin_grp :($adding_profile ?$add_linkedin_grp : null);
$linkedin = $request->linkedin !== null ? $request->linkedin :($adding_profile ?$add_linkedin : null);
$roposo =$request->roposo !== null ? $request->roposo : ($adding_profile ?$add_roposo : null);
$chingari = $request->chingari !== null ? $request->chingari : ($adding_profile ?$add_chingari : null);
$mitron = $request->mitron !== null ? $request->mitron : ($adding_profile ?$add_mitron : null);
$org_name = $request->u_org_slugname;
$u_org_role_id = $request->u_org_role_id;
// $digital_marketer = $request->digital_marketer;
// $bio = $request->bio;
$myimage_trip = DB::table('addprofiles')
->where('user_id', $getting_id)
->update([
'facebook' => $fb,
'twitter' => $twitter,
'youtube' => $youtube,
'wordpress' => $wordpress,
'tumblr' => $tumblr,
'instagram' => $instagram,
'quora' => $quora,
'pinterest' => $pinterest,
'reddit' => $reddit,
'scoopit' => $scoopit,
'slashdot' => $slashdot,
'telegram' => $telegram,
'fb_grp' => $fb_grp,
'linkedin_grp' => $linkedin_grp,
'linkedin' => $linkedin,
'roposo' => $roposo,
'chingari' => $chingari,
'mitron' => $mitron,
// 'digital_marketer' => $digital_marketer,
// 'bio' => $bio,
]);
}
Use Exception handling to avoid error-prone code
Wrap potentially error-prone code inside try-catch blocks to catch exceptions.
Handle different types of exceptions separately based on your application's needs.
try {
// Your code here
} catch (ExceptionType1 $e) {
// Handle specific exception type
} catch (ExceptionType2 $e) {
// Handle another exception type
} catch (\Exception $e) {
// Catch any other exception
}
Use ModelNotFoundException for Database Queries:
When querying for a model and it's not found, use findOrFail or catch the ModelNotFoundException to handle this specific case.
try {
$model = Model::findOrFail($id);
} catch (ModelNotFoundException $e) {
// Handle model not found
}
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class YourController extends Controller
{
public function myorder($id)
{
try {
// Your existing logic to fetch and process the order
$order = Order::findOrFail($id);
// Your other business logic here...
return view('myorder', compact('order'));
} catch (ModelNotFoundException $e) {
// ModelNotFoundException occurs when the model is not found
return response()->view('errors.404', [], 404);
} catch (NotFoundHttpException $e) {
// NotFoundHttpException occurs when the route is not found
return response()->view('errors.404', [], 404);
} catch (\Exception $e) {
// Catch other exceptions (500 Internal Server Error)
logger()->error($e);
return response()->view('errors.500', [], 500);
}
}
}
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
// ...
public function render($request, Throwable $exception)
{
if ($this->isHttpException($exception)) {
return $this->handleHttpException($exception);
}
// Handle other exceptions (e.g., 500 Internal Server Error)
// Log the exception and return a user-friendly response
logger()->error($exception);
return response()->view('errors.500', [], 500);
}
protected function handleHttpException(Throwable $exception)
{
$statusCode = $exception->getStatusCode();
switch ($statusCode) {
case 401:
return response()->view('errors.401', [], 401);
case 403:
return response()->view('errors.403', [], 403);
case 404:
return response()->view('errors.404', [], 404);
default:
return $this->convertHttpExceptionToResponse($exception);
}
}
}
Perform more functionality through less coding
perform create and update through same form
instead of if else use array and for loop
to best performance store data in json format in phpmyadmin
While storing data in JSON format in PHPMyAdmin may be convenient for certain scenarios, it's essential to consider the trade-offs and implications, especially in terms of performance and data integrity. JSON storage in a relational database like MySQL may not always be the most performant option, depending on your use case and how you plan to query the data.
Here's a basic example of how you can store and retrieve JSON data in Laravel using MySQL. In this example, I'll assume you have a users table with a json_data column where you want to store additional JSON data:
Migration:
Create a migration to add a json_data column to your existing users table.
php artisan make:migration add_json_data_to_users_table
In the migration file:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->json('json_data')->nullable();
});
}
Run the migration:
php artisan migrate
Model:
In your User model, make sure the json_data field is included in the $fillable array.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = [
'name',
'email',
'password',
'json_data',
];
// ...
}
Controller:
In your controller, you can now store and retrieve data in JSON format.
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function store(Request $request)
{
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
'json_data' => json_encode(['extra_info' => $request->input('extra_info')]),
]);
return redirect()->route('users.index')->with('success', 'User created successfully!');
}
public function show($id)
{
$user = User::findOrFail($id);
$extraInfo = json_decode($user->json_data, true);
return view('users.show', compact('user', 'extraInfo'));
}
// ...
}
Blade View:
In your Blade view, you can now access the JSON data.
<h1>{{ $user->name }}</h1>
<p>Email: {{ $user->email }}</p>
@if (!empty($extraInfo))
<p>Extra Info: {{ $extraInfo['extra_info'] }}</p>
@endif
Keep in mind that this example uses json_encode and json_decode to convert data to and from JSON format. The $fillable property in the model allows you to mass-assign fields, including the json_data field
Data processing task and bussiness logic use in controller side
avoid php directive to data processing task in blade file use this in controller
Avoid duplicate record from tables
Avoid duplicate record in same table
DB::raw('MAX(social_url.id) as max_id'),
>select(
'social_url.user_id',
DB::raw('MAX(social_url.id) as max_id'),
'social_url.*',
'addcarts.influencer_admin_id',
'addcarts.cart_socials',
'addcarts.admin_id',
'countries.country_name',
'states.state_name',
'cities.city_name'
)
$data = DB::connection('payments')->table("social_url")
->leftJoin('countries', 'social_url.country_id', '=', 'countries.country_id')
->leftJoin('states', 'social_url.state_id', '=', 'states.state_id')
->leftJoin('addcarts', function($join) use ($login_email) {
$join->on('social_url.user_id', '=', 'addcarts.influencer_admin_id')
->where('addcarts.admin_email', '=', $login_email);
})
->leftJoin('cities', 'social_url.city_id', '=', 'cities.city_id')
->where('social_url.user_email', '<>', $login_email)
->select(
'social_url.user_id',
DB::raw('MAX(social_url.id) as max_id'),
'social_url.*',
'addcarts.influencer_admin_id',
'addcarts.cart_socials',
'addcarts.admin_id',
'countries.country_name',
'states.state_name',
'cities.city_name'
)
->groupBy('social_url.user_id')
->orderBy('max_id', 'desc')
->get();
Avoid duplicate record in multiple table while leftjoin
apply multiple condition
leftJoin('addcarts', function($join) use ($login_email) {
$join->on('social_url.user_id', '=', 'addcarts.influencer_admin_id')
->where('addcarts.admin_email', '=', $login_email);
})
$data =DB::connection('payments')->table("social_url")
->leftJoin('countries', 'social_url.country_id', '=', 'countries.country_id')
->leftJoin('states', 'social_url.state_id', '=', 'states.state_id')
->leftJoin(DB::raw('(SELECT MAX(id) AS max_id, influencer_admin_id, cart_socials, admin_id FROM addcarts GROUP BY influencer_admin_id) addcarts'), function($join)
{
$join->on('social_url.user_id', '=', 'addcarts.influencer_admin_id');
})
->leftJoin('cities', 'social_url.city_id', '=', 'cities.city_id')
->select(
'social_url.user_id',
DB::raw('MAX(social_url.id) as max_id'),
'social_url.*',
'addcarts.influencer_admin_id',
'addcarts.cart_socials',
'addcarts.admin_id',
'countries.country_name',
'states.state_name',
'cities.city_name'
)
->groupBy('social_url.user_id')
->orderBy('id', 'desc')
->get();
other way
$login_email = Auth::check() ? Auth::user()->email : null;
->where('social_url.user_email', '<>', $login_email)
->whereNotNull('social_url.social_price')
$filteredData = DB::connection('payments')->table("social_url")
->leftJoin('countries', 'social_url.country_id', '=', 'countries.country_id')
->leftJoin('states', 'social_url.state_id', '=', 'states.state_id')
->leftJoin(DB::raw('(SELECT MAX(id) AS max_id, influencer_admin_id, cart_socials, admin_id FROM addcarts GROUP BY influencer_admin_id) addcarts'), function($join)
{
$join->on('social_url.user_id', '=', 'addcarts.influencer_admin_id');
})
->where('social_url.user_email', '<>', $login_email)
->leftJoin('cities', 'social_url.city_id', '=', 'cities.city_id')
->whereNotNull('social_url.social_price')
->where('social_url.city_id', $city_id)
->leftJoin('users', 'social_url.user_id', '=', 'users.id');
$filteredData->where(function ($query) use ($convertedArray) {
foreach ($convertedArray as $socialSite) {
$query->orWhereNotNull("social_site->$socialSite");
}
});
Top comments (0)