Category Archives: Laravel

Remove public URL on shared hosting | Laravel

Laravel out of the oven is not prepared for being deployed on shared hosting.

I often use shared hosting for testing web apps as it’s the easiest and fastest way of having an app running in WWW.
See bellow what changes are required in order to make Laravel work on shared hosting.

First step is to complete the Laravel setup. You’ll notice that you can access the app by placing /public/ in the URL. This is obviously not fancy at all.

Fix it by replacing the content of .htaccess in the root directory with the code bellow:

<IfModule mod_rewrite.c>
	RewriteEngine on
	RewriteCond %{REQUEST_URI} !^public
	RewriteRule ^(.*)$ public/$1 [L]

That’s all. Remove the /public/ and refresh.

Check my other Laravel posts.

How to build dynamic query in Laravel

Dynamic query allows us to start with a base query and extend it so that we properly filter our data. You probably already used and know what Laravel is and how to create a basic database query.

We’ll cut straight to the problem:

How do we dynamically apply query conditions in Laravel?

Let’s take a look at the following example that I consider quite easy and basic query on a Listing model that has title, description, price, images and date columns:

$title = "planet";
$listings = Listing::where(function($q) use ($title) {
$q->where('title', 'like', $title .'%');

This query will return all our documents for which the title has the form planet% (they start with planet word).

You already knew how to achieve this so let’s extend this to a condition based query generation. Follow bellow:

$title = 'planet;
$price_min = 10;
$price_max = 100;
$listings = Listing::select('title', 'description', 'price', 'images', 'date');

// we're only going to filter by title if it's available
if(isset($title) && !empty($title)) {
$listings->where(function($q) use ($title) {
$q->where('title', 'like', $title.'%');

// but there's more
// what about the price?
if(is_numeric($price_min)) {
$listings->where('price', '>=', $price_min);

We’ve now learned how to build a dynamic query and how to add conditions on the run.

So how do we view our results? 1 line:

$listings = $listings->latest()->get();

That’s it. Now go and build you great app!