Qlic

Qlic

Member Since 4 Years Ago

Experience Points 66,785
Experience Level 14

3,215 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 641
Lessons
Completed
Best Reply Awards 15
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

09 Aug
1 year ago

Qlic left a reply on Validation Does Not Return Error Messages Laravel 5.2.45

@johnnemo i remember facing a similar issue a while back, in my case it was due to an additional redirect which emptied the session before the view would recieve it (remember, the session flash is only stored for 1 redirect).

Your best bet is to dd() every step in your request, or use a custom session instead of flash.

29 Jul
1 year ago

Qlic left a reply on Database Joins Query Problem

Probably because the inner join can't find a matching record. You should look into leftJoin as that will always return the main table even if the joins contain no matching data.

Also, you should look in to the laravel naming conventions, since uppercase characters in your table/field names should be avoided.

16 Jul
1 year ago

Qlic left a reply on Validation Does Not Return Error Messages Laravel 5.2.45

Install BarryvdH debugbar and check the sessions tab to see if it exists there, if not check that your routes use the web middle ware by running php artisan route:list.

Qlic left a reply on Laravel 5.4 Deploy With Cpanel

@vinschi DirectAdmin and cPanel should both support Larvel as long as you have FTP access to the actual domain root, and not just the public directory.

Like you already did, all you have to do i place the Laravel folder in the root, place the public folder contents in the public_html folder (or in your case the www folder), and add the ../ to your index files includes.

Do note that the server is to run at least PHP 5.6.4 and that the public_html folder (www in your case) should be chmodded to 644 or incase that doesn't work 755.

There really isn't anything else you should have to do, however if that still doesn't fix it it's not a problem with Laravel but with your host having some server settings which prevent it from working.

Good luck!

15 Jul
1 year ago

Qlic left a reply on Use Two Foreign Keys Pointing To The Same Table And Retrieve With One Relationship

$user = User::join('trades', function($join) {
    $join->on('users.id', '=', 'trades.user1_id')
        ->orOn('users.id', '=', 'trades.user2_id');
})->get();
01 Jul
1 year ago

Qlic left a reply on Undefined Property:

Apparently your $orders var is either empty or the element in it has no name attribute. So check this, place a dd($orders) in either your controller (before returning the view), or in your view above the foreach.

27 Jun
1 year ago

Qlic left a reply on How To Do This Query In Laravel Query Builder

Is it save to drive a car, no, still people do it. Personally i see no harm in doing so, i've done it in my own projects aswell.

But if you don't, you'll have to use a groupBy, apparently on the users.id field.

Qlic left a reply on How To Do This Query In Laravel Query Builder

Well, that basically comes through strict, simplest way to fix it is to go to config/database and set strict to false.

Qlic left a reply on How To Do This Query In Laravel Query Builder

Ahh oke, than this should be it.

DB::table('application_forms')->join('users', 'application_forms.user_id', '=', 'users.id')
->leftJoin('scores', 'application_forms.id', '=', 'scores.application_id')
->select('users.*', 'application_forms.*')
->selectRaw(DB::raw("COALESCE(AVG(scores.score), 0) AS avg_score"))
->get();

Qlic left a reply on Eloquent Create Doesn`t Fire Event

Also check your model to see if you have the fillables defined.

Qlic left a reply on Auth Forms Load Slow

Probably due to cdn includes whith slow server response.

Qlic left a reply on How To Do This Query In Laravel Query Builder

DB::table('application_forms')->join('users', 'application_forms.user_id', '=', 'users.id')->select('users.*', 'application_forms.*')->selectRaw(DB::raw("AVG(application_forms.score) AS avg_score"))->get();

Qlic left a reply on Eager Loading With Join On Other Tables

Good to hear, it took a while but we got there in the end :P

Qlic left a reply on Eager Loading With Join On Other Tables

@sajjadkharrazi the queries themself look good now though.

Quick question though to debug the (0), in your database have you actually entered an existing location id in the location_id field of the books table?

I've taken a look at my code at work where i do a similar thing, and it's the same type of migrations and model relations, and that works just fine.

26 Jun
1 year ago

Qlic left a reply on Eager Loading With Join On Other Tables

What happens when you change the hasOne location to belongsTo location in the books model

Qlic left a reply on Eager Loading With Join On Other Tables

Haha okay, we'll get there. Then all you have to do is add a location_id to the books table.

Users:
id,
name,
etc.


Books:

id,
user_id,
location_id,
name,
etc.


Locations:
id,
name,
etc.
User model:

hasMany books

-----------

Books model:

belongsTo User
hasOne Location

-----------

Location model:

hasMany Books


Qlic left a reply on Eager Loading With Join On Other Tables

In that case, you will be needing a pivot table after all, since a user can have many books, and a location can have many books.

Migrations

books:

id,
name,
etc.


locations:

id,
name,
etc
.

book_location:

book_id,
location_id

Models

User:

public function books()
{
return $this->hasMany(Book::class);
}


Book:

public function user()
{
return $this->belongsTo(User::class);
}
public function locations()
{
return $this->hasMany(Location::class);
}


Location:

public function books()
{
return $this->hasMany(Book::class);
}

Query:

$books = User::with('books.locations')->get();

Qlic left a reply on Eager Loading With Join On Other Tables

Because the location is a child table to the book, therefore it needs to relate to the book table.

Users table:

id, 
name,
etc.


Books table:

id,
user_id (a book belongs to a user so we bind that here),
name,
etc.


Locations table:

id,
book_id (a location belongs to a book so we bind that here),
name,
etc.

This structure is how you properly normalize your database.

25 Jun
1 year ago

Qlic left a reply on Eager Loading With Join On Other Tables

You're locations table should have book_id, add that and it should work.

P.s. in case your locations (as well as your categories) are shared between multiple books, you will need to create pivot tables (many-to-many relations).

24 Jun
1 year ago

Qlic left a reply on Eager Loading With Join On Other Tables

Post you're entire table structure and models and we'll see whats wrong.

23 Jun
1 year ago

Qlic left a reply on Eager Loading With Join On Other Tables

Assuming you use the proper laravel conventions, meaning a user hasmany books, and books hasOne location, you can chain the with statement.

$userWithBooks = User::with(['books.location'])->get();
22 Jun
1 year ago

Qlic left a reply on Deploying A Laravel Project.

Is the server running at least php 5.6.4?

Qlic left a reply on Limit On The WHERE Col IN (…) Condition

The number of values in the IN list is only limited by the max_allowed_packet value.

https://stackoverflow.com/questions/4275640/mysql-in-condition-limit

11 Jun
2 years ago

Qlic left a reply on Problem Facing With Queue:work On Live Server

Have you solved this? I have the same issue on my server where the processes reach their limit and cause the site to go offline, after that i can't even SSH in as the user forcing me to login as root and kill all processes.

24 May
2 years ago

Qlic left a reply on Blade {{!! !!}} Not Working As Expected

It's either {{ }} for htmlsafe vars or {!! !!} for parsing html.

02 May
2 years ago

Qlic left a reply on Laravel 5.2 - Login Not Workin

Do a php artisan route:list, if the routes don't have the 'web' middleware, add if to your routes group.

Qlic left a reply on Regarding Routing, Web.php Vs Api.php

Personally i use the web file for all things non api related, imo datatables is a 'web request' so it should be in the web route file.

30 Apr
2 years ago
29 Apr
2 years ago

Qlic left a reply on Eloquent's Join

Good for you that through reading the docs you found out about the eager load closures, however in this case it should not be needed since the eager loading automatically binds on the relations.

So in your case, when querying on the model Items, the eager load will look for a column called item_id in the item_details table.

In your code example however, you seem to use itemsModel as the name, which is not following the convention of Laravel/Eloquent.

  1. Tables should be in snakecase, and in the 'multiple' way: user becomes users.
  2. Models are in camelcase, and in the 'single' way: table users has model User.
  3. Tables have a incremental field called id, relations call on this id by simply adding the related name, so user_functions will have id, user_id, etc.
28 Apr
2 years ago

Qlic left a reply on How To Modify Database Connection String In Laravel 5?

I have to start by saying that i personally only use MySQL, however on my project, i needed a second dynamic connection to external databases, so what i did is the following.

In config/database.php you have several option, like sqlite, mysql, pgsql. So i copied the mysql array, renamed it to mysql_source and left the host, user, pass and database empty.

'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'InnoDB',
        ],

        'mysql_source' => [
            'driver' => 'mysql',
            'host' => '',
            'port' => '3306',
            'database' => '',
            'username' => '',
            'password' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

    ],

Then in my controller, i can simply load the (encoded) source mysql credentials from the local database, modify the mysql_source, execute the query and disconnect again.

Example:

config(['database.connections.mysql_source.host' => $source->db_host]);
config(['database.connections.mysql_source.database' => $source->db_database]);
config(['database.connections.mysql_source.username' => $source->db_user]);
config(['database.connections.mysql_source.password' => $source->db_pass]);

$data = DB::connection('mysql_source')
     ->table('some_external_table_name')
     ->get();
DB::disconnect('mysql_source');

Qlic left a reply on Validate Attribute Contains The Value Of Another Attribute

Hmm i see, then i think you will have to resort to a custom validation rule.

https://laravel.com/docs/5.4/validation#custom-validation-rules

Qlic left a reply on Routes And Url

Still, you should really be using the 'as' method like in my reply.

Let's say your URL is like: domain.com/shop/fruits/{fruit}, and you have this url hardcoded in several templates, what happens if the customer wants you to rename it to domain.com/webshop/fruits/{fruit}, you have to replace all your links in your templates because you hardcoded the shop/fruits/{fruit}.

With the 'as' (route('shop.fruit, [$fruit->id]')) method all you have to do is change the routes file and eveything still works.

P.s. i did not involve SEO/.htaccess redirects here.

Qlic left a reply on Routes And Url

I'm having a hard time understaning the problem, however, here's what i always do.

In the routes file:

Route::get('shop', ['as' = 'shop', 'uses' => '[email protected]index']);
Route::get('shop/update-cart', ['as' = 'shop.update.cart', 'uses' => '[email protected]']);

Then in the blade file i use a link like:

<a href="{{ route('shop') }}" title="Cart">Cart</a>

Qlic left a reply on Include Js In Index.blade.php

Well yeah, but the question is should you want to do that. It's best to stick to conventions, and not place your js in random places.

So again, the nicest way to do it is to include the .js file in your master template. This is also the way SEO want it, else you would be getting warnings about inline js code.

However, the projects im working on are private and don't need SEO, so to make my life a bit easier i'm using a javascript yield in my master template, then whenever i need custom javascript i simply add a javascript section to my blade file in which i can use blade commands when needed.

Qlic left a reply on Data Not Inserting Into Database

In your model set the fillable fields.

protected $fillable [
    'name',
    'email',
    'mobile',
    'password',
];

Then for create use:

// Fields not in the $fillable will be ignored
RegisterClient::create($request->all());

For udate use:

if (empty($request->input('password')))
    $user->update($request->except('password'));
else
    $user->update($request->all());

Qlic left a reply on How To Modify Database Connection String In Laravel 5?

Set the values dynamically:

config(['database.connections.mysql.host' => $source->db_host]);
                        config(['database.connections.mysql.database' => $source->db_table]);
                        config(['database.connections.mysql.username' => $source->db_user]);
                        config(['database.connections.mysql.password' => $source->db_pass]);
etc..

Qlic left a reply on Eloquent's Join

Your structure should be like this:

items:

    id
    post_id
    name
    category
    ...

item_details:

    item_id
    description
    ...

item_games:

    item_id
    description
    ...

items would be your main table, in your item model you would have:

public function details()
{
    return $this->hasMany(ItemDetail::class);
}

public function games()
{
    return $this->hasMany(ItemGame::class);
}

Next, in both the ItemDetail and ItemGame models you would have:

public function item()
{
    return $this->belongsTo(Item::class);
}

Qlic left a reply on Concatenate Strings

This should work just fine, as i've used it in my code aswell.

{{ trans('homepage.session_user_name')  .  Auth::user()->name }} 

Qlic left a reply on Include Js In Index.blade.php

You have several options:

  1. Include your .js file in your master template file.
  2. Create a javascript yield in your master, then in your index.blade.php you can add the javascript section.
10 Mar
2 years ago

Qlic started a new conversation How Do I Access A Pivot With A Pivot Through My Models

I have three tables that need to work together.

  • users
  • projects
  • vehicles

a project can have many vehicles. a vehicle can have many projects. a vehicle can have many users. a user can have many vehicles.

I have the following models:

  • User
  • Project (belongsToMany Vehicle)
  • Vehicle (belongsToMany Project)
  • VehicleUser (belongsToMany Project & hasManyThrough User, Vehicle)

The hasManyThrough does not seem to work due to the fact that the id's are not like the laravel docs example.

My table structure is illustrated in the following image: http://i63.tinypic.com/mvrqt5.png However i can't figure out how to retrieve the users bound to each vehicle bound to a project.

How do you guys go about doing this?

04 Sep
2 years ago

Qlic left a reply on Retrieve Model Based On The "created_at" Timestamp

That's because you are matching on an exact date and time. If you want to match on date only, use something like

$today = Carbon::today();
$search = $today->subDay(1)->format('Y-m-d');
$loading = LoadingBus::where('created_at', 'LIKE', $search.'%')->get();
16 Aug
2 years ago

Qlic started a new conversation Correct Usage Of A MySQL OR Statement

I'm having a bit of a struggle here with something that ( i'm guessing) shouldn't be so hard, and so i'll do my best to explain.

Let's start with the basic table i'm using:

id, cns_id, client_id, subordinates, ppc, pps, valid_from etc.
----------------------------------------------------------------
1, 316, null, null, 0.0200000000, 0.0083333333, null
2, 316, 170, 1, 0.0200000000, 0.0012500000, 2016-01-01

In my query i want to say the following: For the user with a client_id of 170, subordinates of 1, cns_id of 316, fetch me the ppc and pps values, HOWEVER incase there is no entry matching that request, fetch me the default for cns_id 361 which has a client_id of NULL, a subordinates of NULL.

Translated to Laravel i came up with the the following:

                $q = $cns->rates()
                    ->with(['otherCns.rates' => function($q) use ($item) {
                        $this->applyCriteria($q, $item->client_reseller_id, $item->start);
                    }]);
                $rates = $this->applyCriteria($q, $item->client_reseller_id, $item->start)->first();

   protected function applyCriteria($q, $id, $start, $type = 'reseller')
    {
        if ($type == 'reseller') {
            $q->where(function($q) use ($id) {
                $q->where('cns_rates.client_id', '=', $id)
                    ->whereNull('cns_rates.subordinates')
                    ->orWhere(function($q) use ($id) {
                        $q->whereNull('cns_rates.client_id')
                            ->whereNull('cns_rates.subordinates');
                    });
            });
        } else {
            $q->where(function($q) use ($id) {
                $q->where('cns_rates.client_id', '=', $id)
                    ->where('cns_rates.subordinates', '=', '1')
                    ->orWhere(function($q) use ($id) {
                        $q->whereNull('cns_rates.client_id')
                            ->whereNull('cns_rates.subordinates');
                    });
            });
        }

       $q->where(function($q) use ($start) {
                $q->where('cns_rates.valid_from', '<=', $start)
                    ->orWhereNull('cns_rates.valid_from');
            })
            ->orderBy('cns_rates.valid_from', 'desc');

        return $q;
    }

Translated to the actual query (using toSql()) i get the following:

select 
    * 
from 
    `cns_rates` 
where 
    `cns_rates`.`cns_id` = ? 
and 
    `cns_rates`.`cns_id` is not null 
and 
    (
            `cns_rates`.`client_id` = ? 
        and 
            `cns_rates`.`subordinates` is null 
        or 
            (
                    `cns_rates`.`client_id` is null 
                and 
                    `cns_rates`.`subordinates` is null
            )
    ) 
and 
    (
            `cns_rates`.`valid_from` <= ? 
        or 
            `cns_rates`.`valid_from` is null
    ) 
order by 
    `cns_rates`.`valid_from` 
desc

Now comes the dilemma, i have the feeling the OR statement always overwrites whatever the where statement already might have found (the client specific data), this i always end up with a value of 0,050 cents per minute, where in this case i'm expecting the query to return me 0,075 cents per minute.

I'm sure there is a logic error in my query, but i have no clue as to how to solve it, so i'm hoping some SQL guru can help me with this, because i would like to prevent having to write double query's.

08 Aug
2 years ago

Qlic left a reply on Weird MySQL Issue

If bio is set to not null, and you are performing an insert query without specifiying a value for bio, than you will indeed get an error about that specific field. So you will need to do one of three things.

  1. Set a default value for bio.
  2. Set bio as nullable.
  3. Specify a value for bio in your query.
05 Aug
2 years ago

Qlic left a reply on Submitting A Form With 2 Buttons

Your route is set as post, and you "submit" your form as a get path, that results in MethodNotAllowedHttpException . If i were you, i'd use buttons instead of hrefs, and use jquery to sumib the form method you want.

30 Jul
2 years ago

Qlic left a reply on 422 (Unprocessable Entity) In Laravel With Vuejs

422 should not be seen as an "error", it's simply the response code laravel returns when validation fails. If you were to inspect the element in lets say firebug, you would see the validation rules there of the failed request.

19 Jul
2 years ago

Qlic left a reply on DOMPDF And Loading Routed Images

@SaeedPrez i read that, but i'm currently not even testing it on DOMPDF, i wanted to see wether or not calling both the route and method worked, so i created a plain blade template, which i call through a controller, so without DOMPDF.

When both of those work, than i'll be able to shift my focus to getting it to work in DOMPDF aswell.

  • EDIT: It's working now, i altered my method to return base64 encoded data, and this works in both a regular template ánd in the DOMPDF template, so in the end, SaeedPrez you helped me alot by changing the image response to within a helper function.

Qlic left a reply on DOMPDF And Loading Routed Images

@DivDax well yes, that works, however than everyone can still access my images, which is exactly what i want to prevent.

Qlic left a reply on DOMPDF And Loading Routed Images

@SaeedPrez i don't get any error messages, also i'm testing the method directly inside a regular template view to make sure wit works without a call to the route, so this is even before it's called in DOMPDF.

Also i tried the strorage get, same story, the img src remains empty, but when i diedump the call, it does contain data.

<?php

namespace App\Helpers;

use Image;
use Storage;

class Helper
{
    public static function displayPhoto($lead, $type, $name, $plain=null)
    {
        switch($type) {
            case 1:
                $folder = 'roof';
                break;
            case 2:
                $folder = 'meterboard';
                break;
            case 3:
                $folder = 'access';
                break;
            case 4:
                $folder = 'converter';
                break;
            case 5:
                $folder = 'cable';
                break;
        }

        if ($plain) {
            return Storage::get('photo/'. $lead .'/'. $folder .'/'. $name);
        }

        return Image::make(storage_path() . '/app/photo/'. $lead .'/'. $folder .'/'. $name)->response();
    }
}

Qlic left a reply on DOMPDF And Loading Routed Images

After doing some further testing, here's what i found:

  1. From a regular template, calling the image route does return an image
{!! Html::image(route('inventory.photo', [$foo, $bar, $bla])) !!}  // shows image as expected
  1. From the same regular template, calling the image method does not return an image, or at least not as expected.
<img src="{{ Helper::displayPhoto($foo, $bar, $bla) }}" /> // src remains empty, however, when i place a return 'test'; inside the method, source does show test, so at least i know it's inside the method.

{{ dd(Helper::displayPhoto($foo, $bar, $bla)) }} // shows me image data