kingmaker_bgp

kingmaker_bgp

Member Since 2 Years Ago

Kanyakumari

Experience Points
26,000
Total
Experience

4,000 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
166
Lessons
Completed
Best Reply Awards
13
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 6
26,000 XP
Oct
26
3 days ago
Activity icon

Awarded Best Reply on How To Keep Session Between 2 HTTP Tests?

I think you are missing being Logged In between 2 requests.

$user = User::find(1);
$this->actingAs($user);

$this->followingRedirects()
            ->post('/new-appointment', [
                '_token' => csrf_token(),
                'user_id' => $user->id,
                'start_at' => Carbon::now()->startOfWeek()->addDays(7)->setTime(10, 0, 0)->format('Y-m-d H:i:s'),
            ])
            ->assertSee('10:00');

        $this->get('/connection')
            ->assertSee('10:10');
Activity icon

Replied to How To Keep Session Between 2 HTTP Tests?

I think you are missing being Logged In between 2 requests.

$user = User::find(1);
$this->actingAs($user);

$this->followingRedirects()
            ->post('/new-appointment', [
                '_token' => csrf_token(),
                'user_id' => $user->id,
                'start_at' => Carbon::now()->startOfWeek()->addDays(7)->setTime(10, 0, 0)->format('Y-m-d H:i:s'),
            ])
            ->assertSee('10:00');

        $this->get('/connection')
            ->assertSee('10:10');
Activity icon

Awarded Best Reply on How To Retrieve JSON Data In Controller: Laravel

This is because you are passing the Form Data as a JSON body with the contactDetails as the first level key.

you can pass the Form Data as the request body like below

onSubmit(evt) {
        let contactDetails = JSON.stringify(this.form);
        this.$http.post('api/contact/form/submit', contactDetails).then( (res) => {
            console.log(res);
        }).catch( (err) => {
            console.log(err);
        })
      },

This lets you access all the values as magic Properties on the Request object (email, name, subject, depart, issue, checked)

$email = $request->email;
// OR
$email = $request->input('email');

$name = $request->name;
// OR
$name = $request->input('name');

// etc...
Activity icon

Replied to Social Login - Record In Database, In The Users Table In Password Field

Just leave the password field empty NULL and add the columns to store the Provider details

- Provider Name (Facebook, Google or Github)
- Provider ID
Activity icon

Replied to How To Retrieve JSON Data In Controller: Laravel

This is because you are passing the Form Data as a JSON body with the contactDetails as the first level key.

you can pass the Form Data as the request body like below

onSubmit(evt) {
        let contactDetails = JSON.stringify(this.form);
        this.$http.post('api/contact/form/submit', contactDetails).then( (res) => {
            console.log(res);
        }).catch( (err) => {
            console.log(err);
        })
      },

This lets you access all the values as magic Properties on the Request object (email, name, subject, depart, issue, checked)

$email = $request->email;
// OR
$email = $request->input('email');

$name = $request->name;
// OR
$name = $request->input('name');

// etc...
Oct
24
5 days ago
Activity icon

Awarded Best Reply on Problem With Voyager Onlt On Server, Not Localhost

did you install the new package (refresh vendor folder) on the server?

composer install
Activity icon

Replied to Problem With Voyager Onlt On Server, Not Localhost

did you install the new package (refresh vendor folder) on the server?

composer install
Activity icon

Replied to Form Submission On Old Values

@dk4210, just compare the $application->id within the @foreach loop to the DB Query value.

If you want to use both the Database Query and old() function, then I guess you are trying to use the Same View for create and update functions.

If so, just make sure which value to select in a variable within the blade and compare against it

@php
$selectedApplicationId = isset($applicationFromDbQuery) ? $applicationFromDbQuery->id : old('application_id');
@endphp

<select class="form-control" id="application_id" name="application_id" required>
<option value="">Please choose an application</option>
  @foreach(App\Application::all() as $application)
@if($application->deleted == 0 && $application->status != 0)
  <option value="{{$application->id}}" @if($application->id == $selectedApplicationId) selected @endif>{{$application->name}}</option>
  @endif                                                
 @endforeach
 </select>
Activity icon

Replied to Form Submission On Old Values

Sorry @dk4210, I didn't see laracast for a day. I didn't get what you mean by the following?

So what if I wanted it to select the choice based on the database query?

If you want a particular <option> element to be selected, just make sure the blade puts the selected attribute on that <option>

The below logic is completely wrong

@if($application->id == $application->id) selected @endif

Did you mean to select a value based on another Eloquent or Database query?

Oct
22
1 week ago
Activity icon

Awarded Best Reply on Form Submission On Old Values

you can use the HTML selected attribute here

<label for="application">{{ __('Application')}}</label>
<select class="form-control" id="application_id" name="application_id" required>
   <option value="">Please choose an application</option>
   @foreach($applications as $application)
       @if($application->deleted == 0 && $application->status != 0)
           <option value="{{$application->id}}" @if(old('application_id') == $application->id) selected @endif>{{$application->name}}</option>
       @endif                                                
    @endforeach
</select>
Activity icon

Replied to Form Submission On Old Values

you can use the HTML selected attribute here

<label for="application">{{ __('Application')}}</label>
<select class="form-control" id="application_id" name="application_id" required>
   <option value="">Please choose an application</option>
   @foreach($applications as $application)
       @if($application->deleted == 0 && $application->status != 0)
           <option value="{{$application->id}}" @if(old('application_id') == $application->id) selected @endif>{{$application->name}}</option>
       @endif                                                
    @endforeach
</select>
Oct
17
1 week ago
Activity icon

Replied to Query On Created_at With Carbon

Sorry I couldn't be of help, I haven't used Mongo before...

Activity icon

Replied to Str_replace

Your Requirement seems like an old school core PHP task. You can print(echo) without default blade HTML encoding.

{!! str_replace('___', '<input name="answers[]" />', $question) !!}
Activity icon

Replied to Query On Created_at With Carbon

which Database driver were you using?

Activity icon

Replied to Query On Created_at With Carbon

@hala, If you need to query Community created specific days before, you can use the ::whereDate function

Community::whereDate('created_at', Carbon::now()->subDays(3))
Activity icon

Replied to Str_replace

@jeevamugunthan, your question is not clear.

Sep
29
1 month ago
Activity icon

Replied to How To Define The Name Of The Key Parameter

Also, you can use a shorthand in passing the Route parameters to the route() function with just a plain PHP Array

action="{{ route('head.update', [$data->id]) }}"
Activity icon

Replied to How To Define The Name Of The Key Parameter

The Route Parameters will use the resource name specified in the Route::resource('resource', 'Controller') in their routes.

So you have to use

action="{{ route('head.update', ['head' => $data->id]) }}"
Activity icon

Replied to 1 Instance Of Laravel With Multiple Subdomains

@artcore, If you want to use seperate Databases under different Sub-Domain, you need to use different Laravel application codebase for each.

Use the Same code under each sub-domain directory and use different .env files under each

The Goal of the Question is to have a website separated under various sub-domains like

  • website.com
  • admin.website.com
  • customer_portal.website.com

and have them all served by the Same Laravel application.

Sep
28
1 month ago
Activity icon

Replied to 1 Instance Of Laravel With Multiple Subdomains

@artcore, If you are doing wildcard records in the DNS Entries and you said you have separate folder for each sub-domain in public_html directory, you are doing it completely wrong, my friend

If you want all the sub-domain to be handled by same code (same Laravel applications), then you want to route the Requests to all Sub-Domains to be the very same public folder of Laravel.

I usually use Apache web serevr and have virtual Host configuration like

<VirtualHost *:80>
  DocumentRoot /var/www/application
  ServerName application.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/application
  SeverName wildcard.application.com
  ServerAlias *.application.com
</VirtualHost>
Activity icon

Replied to Laravel 8.x App Deployment To VPS LAMP Server

If you are using an Virtual Machine, you can able to edit the Apache Site Configuration files in /etc/apache2/sites-available/ directory to point to the public folder of Laravel application.

If you were using the managed VPS provided by various Hosting Providers, you can raise a Support Ticket for them to do do OR you can do it yourself.

Sep
27
1 month ago
Activity icon

Replied to 1 Instance Of Laravel With Multiple Subdomains

You have to define the routes clearly(sub-domain has to be a fully qualified name and use Route Names) in the routes file.

Route::get('/', [HomeController::class, 'index']);

Route::domain('admin.' . config('app.url'))
	->name('admin.')
	->group(function() {
		Route::('link-to-send-in-email', [AdminController::class, 'action'])
			->name('email.clickable');
	});

Then in the Views, you can use the route() method

{{-- In the View file --}}

...
<a href="{{route('admin.email.clickable')}}" target="_blank">
	Admin Area
</a>
Activity icon

Replied to 1 Instance Of Laravel With Multiple Subdomains

If that's the case, you have to set it to www.domain.com. Because this value will be used in the Mails as you said.

Activity icon

Replied to 1 Instance Of Laravel With Multiple Subdomains

Hi @laracoft,

I recommend setting the APP_URL to be the base URL (ie, primary domain)

# Development 
APP_URL=localhost:8000

# Production
APP_URL=your_domain.com
Activity icon

Replied to Custom Route File Laravel 8 Not Working As Intended

@abdulrehmandev, not all the PHP Files in the routes/ folder will be loaded for Routing. Laravel by default loads only 4 files

  1. api.php
  2. channels.php
  3. console.php
  4. web.php

These files were loaded in the App\Providers\RouteServiceProvider class. If you need to add custom file (admin.php), you need to register it in the RouteServiceProvider

You can do that in the boot() method of App\Providers\RouteServiceProvider

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api')
                ->group(base_path('routes/api.php'));

            // new code HERE
            Route::middleware('web')
                ->group(base_path('routes/admin.php'));
            // new code ENDS HERE
        });
    }
Sep
25
1 month ago
Activity icon

Replied to Printing Table Without Knowing Column Names?

Hi @andyandy, you can get the Column Name in the @foreach like below

@unless($randomTable->empty())
<table>
	<thead>
	<tr>
		@foreach(array_keys($randonTable->first()->getAttributes()) as $cloumnName)
		<th>{{ $columnName }}</th>
		@endforeach
	</tr>
	</thead>
	<tbody>
	@foreach($randomTable as $item)
	<tr>
		@foreach($item->getAttributes() as $cloumn => $value)
		<td>{{ $value }}</td>
		//
                // $column
                // Here you have it :-)
                //
		@endforeach
	</tr>
	@endforeach
	</tbody>
@else
No Data
@endunless

The ->getAttributes() function returns an Associative array, which (when print_r()) look like below

[
	['column1'] => 'value1',
	['column2'] => 'value2',
	.
	.
	.
	['columnn'] => 'valuenn'
]
Activity icon

Awarded Best Reply on Printing Table Without Knowing Column Names?

you can use the method ->getAttributes() method on the Eloquent Model instance to get the $attributes (associative array of the row value).

So, you can do

@unless($randomTable->empty())
<table>
	<thead>
	<tr>
		@foreach(array_keys($randonTable->first()->getAttributes()) as $cloumnName)
		<th>{{ $columnName }}</th>
		@endforeach
	</tr>
	</thead>
	<tbody>
	@foreach($randomTable as $item)
	<tr>
		@foreach($item->getAttributes() as $value)
		<td>{{ $value }}</td>
		@endforeach
	</tr>
	@endforeach
	</tbody>
@else
No Data
@endunless
Activity icon

Replied to Printing Table Without Knowing Column Names?

you can use the method ->getAttributes() method on the Eloquent Model instance to get the $attributes (associative array of the row value).

So, you can do

@unless($randomTable->empty())
<table>
	<thead>
	<tr>
		@foreach(array_keys($randonTable->first()->getAttributes()) as $cloumnName)
		<th>{{ $columnName }}</th>
		@endforeach
	</tr>
	</thead>
	<tbody>
	@foreach($randomTable as $item)
	<tr>
		@foreach($item->getAttributes() as $value)
		<td>{{ $value }}</td>
		@endforeach
	</tr>
	@endforeach
	</tbody>
@else
No Data
@endunless
Activity icon

Replied to Getting Error While Trying To Run "composer Require --dev Laravel/ui"

No @andyandy, It should install Laravel 8 as it was made Stable on September 8

If you want to create a project with specific version, use

composer create-project laravel/laravel=<version here> someproject
Activity icon

Awarded Best Reply on Getting Error While Trying To Run "composer Require --dev Laravel/ui"

the lates version of laravel/ui you were trying to install depends on Laravel 8.x, but you are using laravel 7.x

try installing older version of laravel/ui

composer require --dev laravel/ui:2.*
Sep
24
1 month ago
Activity icon

Replied to Getting Error While Trying To Run "composer Require --dev Laravel/ui"

the lates version of laravel/ui you were trying to install depends on Laravel 8.x, but you are using laravel 7.x

try installing older version of laravel/ui

composer require --dev laravel/ui:2.*
Activity icon

Replied to Sending Mails Without Smtp - Laravel 7

You want to send Email without using any external Mail Servers (SMTP, SendGrid) ? just like a plain old PHP mail ( string $to , string $subject , string $message)?

Please do read below...

Brief History of SMTP (E-Mail Protocol)

The Simple Mail Transfer Protocol (SMTP) was a very old Protocol for sending E-Mail over Internet, invented in 1982. The SMTP Protocol doesn't have any strict Standards.

That mean, I can send an SMTP packet over Internet with whatever I want like following cases:

You can clearly see the above cases are absolutely Horrible and the SMTP protocol permits this

Blocking Spam / Scam / False E-Mail

In order to avoid such E-Mail, The E-Mail Receiver Servers (also called as Mail eXchange (MX) Server) like Gmail, Outlook, Yahoo, etcs checks for the Credibility of the received E-Mails by checking the Sender's IP and Security mail headers.

These IP / Sender Verification is done by means of an SPF Record and DKIM Record in the DNS of the respective yourdomain.com. These Record will be pre-populated by every Hosting Provider to allow successful sending of the E-Mail from [email protected].

In case these Records doesn't match with the received E-Mail, the E-Mail providers (Gmail, Outlook) will simply reject the Mail and won't even appear on the Spam folder. This is what happens mostly when we use native php mail() function.

Need for an SMTP Relay for successful E-mails

To avoid, these complications we use SMTP, SendGrid & other services to send E-mail successfully from Laravel.

Activity icon

Replied to Best Way To Get Datetime-local Current Time...

Hi @ollie_123, please have a look at the Date Format Validation Rule if the Validation is the one that keeps you bouncing back

Activity icon

Replied to Compare Sum Of Relational Column

Hi @shineraj, you can achieve this using Nested WHERE Clause in the Eloquent Query.

use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use App\Model\User;

$fully_paid_users = User::where(function (Builder $query) {
		return $query->selectRaw('SUM(`amount`)')
			->from('payments')
			->whereColumn('user_id', 'users.id');
	}, DB::raw('amount_to_be_paid'))
	->get();

This works only on Laravel 7.x & above

Documentation

Sep
19
1 month ago
Activity icon

Awarded Best Reply on Dynamic/conditional Relationships

Hi @schwartzmj, I can clearly see your Confusion with these answers. I don't blame you nor Laravel.

Its tough to grab a clear distinction in most Laravel Classes like when they behave as Database Query or as Eloquent Object

The Relationships work on Database (SQL) Query Level, so you don't have access to the Column values within your Functions (Relations & Query Scopes).

Always remember the Database is hit only on ->get() or ->first() method calls. So while during the whole chaining calls, the expression acts as a Eloquent Query Instance.

This is how things work in your case

  1. The static call User::where('role', 'family') returns an Eloquent Query instance
  2. next static call ->with('applications') will modify (mutate TBP) this query to add an Relation to eager loaded
  3. So In this phase, the Laravel Eloquent Query Instance expects your relationship function to work on a SQL Query level (where the column values of each row is still unknown)
  4. when the ->get() method is called, the Database query is executed.
  5. The SQL Query is executed on the users table
  6. Eloquent Query Instance will construct the corresponding Model (User) Instances and put them as Collection and returns.
  7. since it has eager loading specified, Laravel tries to eager load the related table rows in a most efficient way (single query)
  8. This is now the Laravel framework will try to use the specified Relationship. Since It is going to execute the SQL Query on the related table, It expects your relation function to provide it a SQL query (It is important to note, Laravel expects a single SQL Query).
  9. This point the checks if ($this->role === 'family') and if ($this->role === 'agency') fails, since this is applied on a Eloquent Query instance, not on a Eloquent Model instance.

This is how your code is causing Problem. If you need further clarification, please feel free to reply back :-)

If you want to avoid Exception (but will not work), modify relationship as below

    public function applications()
    {
        if ($this->role === 'family') {
            return $this->hasMany(Application::class, 'family_id');

        if ($this->role === 'agency') {
            return $this->hasManyThrough(Application::class, User::class, 'agency_id', 'family_id');
        }

	if ($this->role === 'admin')
	{
		throw new \Exception('User is not an "agency" or a "family", so has no Applications.');
	}
}

The Above code will always return Empty Collection when using eager loading. But will atleast work on individual Model instance like $family->applications, $agency->applications.

Activity icon

Replied to Dynamic/conditional Relationships

Hi @schwartzmj, I can clearly see your Confusion with these answers. I don't blame you nor Laravel.

Its tough to grab a clear distinction in most Laravel Classes like when they behave as Database Query or as Eloquent Object

The Relationships work on Database (SQL) Query Level, so you don't have access to the Column values within your Functions (Relations & Query Scopes).

Always remember the Database is hit only on ->get() or ->first() method calls. So while during the whole chaining calls, the expression acts as a Eloquent Query Instance.

This is how things work in your case

  1. The static call User::where('role', 'family') returns an Eloquent Query instance
  2. next static call ->with('applications') will modify (mutate TBP) this query to add an Relation to eager loaded
  3. So In this phase, the Laravel Eloquent Query Instance expects your relationship function to work on a SQL Query level (where the column values of each row is still unknown)
  4. when the ->get() method is called, the Database query is executed.
  5. The SQL Query is executed on the users table
  6. Eloquent Query Instance will construct the corresponding Model (User) Instances and put them as Collection and returns.
  7. since it has eager loading specified, Laravel tries to eager load the related table rows in a most efficient way (single query)
  8. This is now the Laravel framework will try to use the specified Relationship. Since It is going to execute the SQL Query on the related table, It expects your relation function to provide it a SQL query (It is important to note, Laravel expects a single SQL Query).
  9. This point the checks if ($this->role === 'family') and if ($this->role === 'agency') fails, since this is applied on a Eloquent Query instance, not on a Eloquent Model instance.

This is how your code is causing Problem. If you need further clarification, please feel free to reply back :-)

If you want to avoid Exception (but will not work), modify relationship as below

    public function applications()
    {
        if ($this->role === 'family') {
            return $this->hasMany(Application::class, 'family_id');

        if ($this->role === 'agency') {
            return $this->hasManyThrough(Application::class, User::class, 'agency_id', 'family_id');
        }

	if ($this->role === 'admin')
	{
		throw new \Exception('User is not an "agency" or a "family", so has no Applications.');
	}
}

The Above code will always return Empty Collection when using eager loading. But will atleast work on individual Model instance like $family->applications, $agency->applications.

May
29
5 months ago
Activity icon

Replied to New Model Vs Model::query()

No @dams, It will return a Eloquent Query Builder Instance which represents the Database Query for the User model.

  1. It hasn't made any Database Queries yet
  2. To make the Query and get the Results, You have to chain either ->get() method to get all rows as an Eloquent User Collection or use ->first() to get First row as User Instance.

To put it into simple Layman's terms, It is similar to \DB::table('users') but with the User Model tied to the Query.

If you didn't get the following part

with the User Model tied to the Query

It means any further chaining methods will return the result as an instance of App\User class...... rather than Instance of PHP stdClass class which the \DB::table('users')->get() or \DB::table('users')->first() does