WHERE clause with Special character in MySQL and PHP query and prepared statement

Special character issue in php query can be solved by using:

WHERE _utf8'string'

https://dev.mysql.com/doc/refman/8.0/en/string-literals.html

this unfortunately does not work for prepared statement.

Instead set the character set for the connection to utf-8 using

$conn->set_charset("utf8")

https://www.php.net/manual/en/mysqli.set-charset.php

if (!$conn->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $conn->error);
    exit();
} else {
    printf("Current character set: %s\n", $conn->character_set_name());
}

If your string might include backslash, escaping the string will do the trick:

$city = mysqli_real_escape_string($link, $city);

php.net/manual/en/mysqli.real-escape-string.php

Date and time in php: common function

Convert a date in a timestamp:

strtotime ( string $datetime [, int $now = time() ] ) : int

https://www.php.net/manual/en/function.strtotime.php

Add an arbitrary amount of time in a string format:

strtotime("+1 week"), "\n";

$availability_date=get_post_meta( get_the_ID(), 'availability date', true );
$date_string=strval($availability_date);
$date_string.=" +3 weeks";
$date=new DateTime;
$diplay_time= date('d-m-Y',strtotime($date_string)) ;
$availability_date=strtotime($availability_date);

What is a “Final Class” in php?

“PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended”

https://www.php.net/manual/en/language.oop5.final.php#:~:text=PHP%205%20introduces%20the%20final,then%20it%20cannot%20be%20extended.&text=Note%3A%20Properties%20and%20constants%20cannot,may%20be%20declared%20as%20final.

Add the url parameters for Laravel search results pagination

Issue: If you paginate your search result, when clicking on the 2 page, or any other nth page of your pagination link, it will return an url with the page parameter but without your search parameter. This cause your filtering to be lost.

Solution:

Make sure to return your parameter variable from the controller function as you will need to call it on your blade view.

return view('my_view',compact( 'queryResult','my_variable'));

In your view:

@foreach($queryResult   as $stuff)
     {{$stuff->stuff_name}}
 @endforeach
{{$ queryResult ->appends(['search_variable=>$my_variable])->links('vendor.pagination.materializecss')}}

if you have several URL parameters you can align the ->appends() one after the other. Don’t forget to ad the varaible to the view in the controller.

Passing variables to Laravel parameter grouping function

Issue: A statement such as

$nb_votes = $request->input('nb_votes');
DB::table('users')
            ->where('name', '=', 'John')
            ->where(function ($query) {
                $query->where('votes', '>', $nb_votes)
                      ->orWhere('title', '=', 'Admin');
            })
            ->get();

will return an error:

Unknown variable $nb_votes 

The issue is due to the fact that $nb_votes in the anonymous function refers to the local scope, while the variable we want to use has been defined outisde of the function. We need to pass the variable to the anonymous function.

Solution: To pass a variable to an anonymous function you can do as follow:

$nb_votes = $request->input('nb_votes');
DB::table('users')
            ->where('name', '=', 'John')
            ->where(function ($query) use ( $nb_votes ) {
                $query->where('votes', '>', $nb_votes)
                      ->orWhere('title', '=', 'Admin');
            })
            ->get();

https://www.php.net/manual/en/functions.anonymous.php

see last example in example #3

For laravel queries documentation:

https://laravel.com/docs/5.8/queries#parameter-grouping

Login with Facebook in Laravel 5.8

To add social media login functionality to Laravel 5.8, one library come over and over again, it’s socialite.

https://github.com/laravel/socialite

SSH into your server and run the following command in the directory where your Laravel is installed:

composer require laravel/socialite

As composer is locked after install. I needed to reinstall completely. On my host, the installation needs to be global for it to work (or at least, a local install did not do the trick). So I ran

composer global remove laravel/installer
composer global require laravel/installer laravel/socialite
cd Path/to/my/directory
laravel new ProjectName --auth

without global, laravel was an unknown command.

Official documentation can be found on the Laravel website:

https://laravel.com/docs/6.x/socialite

Additional resources:

https://medium.com/@confidenceiyke/laravel-5-8-facebook-socialite-authentication-8863b9a43f11

https://getcomposer.org/doc/01-basic-usage.md

https://getcomposer.org/doc/03-cli.md

https://getcomposer.org/doc/01-basic-usage.md

Add google Recaptcha control on login form in Laravel

To implement Google Recaptcha in Laravel check our article on implementing Google Recaptcha for Laravel registration.

in /app/Http/Controllers/Auth/LoginController.php

Add the following lines:

use Illuminate\Http\Request;
use App\Rules\GoogleRecaptcha;

And before theclosing curly brackets:

/** 
* Validate the user login request. 
* 
* @param  \Illuminate\Http\Request  $request 
* @return void 
*/ 
protected function validateLogin(Request $request) 
{ 
    $this->validate($request, [ 
    $this->username() => 'required|string', 
    'password' => 'required|string', 
    'g-recaptcha-response' => ['required', new GoogleRecaptcha], 
    ]); 
}

Login with user name instead of email in Laravel

Default laravel login is set to work with email and password but there might be some instance where login with an email address is not desirable and you might want to change this to login with a username.

The advantage of logging in with an email address is that you can be sure it will be unique. The drawback is that it is a bit long to type and some people are not comfortable giving their email address, so depending on your type of application, where having the email address is not essential, it makes sense to offer to login with a username instead.

In Laravel 5.8

Add the following function in app/Http/Controllers/Auth/LoginController.php

/**
*Use username instead of default (email address)
*for authentication
**/
public function username(){
    return ('name');
}

in the return(‘name’) statement, ‘name’ stand for the column name in your user table in your database you want to use. In my case the column is ‘name’.

in resources/views/auth/login.blade.php change the email login field with a username field as follow:

<div class="form-group row">
    <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
    <div class="col-md-6">
       <input id="name" type="text" class="form-control" name="name" required>
  </div>
</div>

As you are now using the username instead of the email for logging in, you need to make sure the username is the unique. To do that you will need to modify your migrations file for create_users_table.php

table->string('name')->unique(); 

And you are all set.