CodebyRay

CodebyRay

Freelance Web Developer at CodebyRay (Myself)

Member Since 2 Years Ago

Experience Points
8,780
Total
Experience

1,220 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
10
Lessons
Completed
Best Reply Awards
9
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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 2
8,780 XP
Dec
30
9 months ago
Activity icon

Replied to Subdomain Working But Domain Is Not

Have you tried moving the main domain group route above your subdomain group? I think if i'm not mistaken it is the order you have them in.


Route::domain('domain.com')->group(function () {


Route::group(['middleware' => ['web', 'auth']], function () {

    Route::get('/', '[email protected]')->name('index');

});

});

Route::domain('{blog}.domain.com')->group(function () {
    
    Route::get('/', function () {
        echo session()->get('blog.slug');
    });

});

Dec
28
9 months ago
Activity icon

Replied to Confirmation Delete Data Using SweetAlert With Laravel 5.7

What’s in your scripts file? Are you including jquery?

Add this before your Ajax call:

(function(document, window, $) {
                'use strict';
                var Site = window.Site;
                $(document).ready(function() {
                    Site.run();
                });
            })(document, window, jQuery);

As @globals said make sure your including jquery in your page before any of these.

Hope this helps.

Activity icon

Replied to Confirmation Delete Data Using SweetAlert With Laravel 5.7

@FAREEDR - I forgot the closing ); in the Ajax.

$.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

I fixed it in the other reply as well.

Activity icon

Replied to Confirmation Delete Data Using SweetAlert With Laravel 5.7

Here is my setup and it works without issues:

$.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

function confirmDelete(inventoryId, dealerId) {
            swal({
                title: "Confirm Delete",
                text: "Are you sure you want to delete this vehicle from inventory?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: false
            }, function (isConfirm) {
                if (!isConfirm) return;
                $.ajax({
                    url: '{!! route('dealer::inventory.delete.post') !!}',
                    type: "POST",
                    data: {
                        id: inventoryId,
                        dealerId: dealerId
                    },
                    dataType: "text",
                    success: function () {
                        swal({title: "Success", text: "Vehicle has been deleted! \nClick 'Ok' to refresh page.", type: "success"},
                            function(){ 
                                location.reload();
                            }
                        );
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Error!", "Please try again", "error");
                    }
                });
            });
        }

Hope this helps.

Activity icon

Replied to Confirmation Delete Data Using SweetAlert With Laravel 5.7

@FAREEDR - Take out the stuff you have in your function as above. I edited to show what to remove.

Regards, Ray

Activity icon

Replied to Confirmation Delete Data Using SweetAlert With Laravel 5.7

Try adding this before your deleteData(id) function:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    });

function deleteData(id){
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this imaginary file!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
            .then((willDelete) => {
                if (willDelete) {
                    $.ajax({
                        url : "{{ url('posts')}}" + '/' + id,
                        type : "POST",
                        data : {'_method' : 'DELETE'},
                        success: function(data){
                            swal("Poof! Your imaginary file has been deleted!", {
                            icon: "success",
                            });
                        },
                        error : function(){
                            swal({
                                title: 'Opps...',
                                text : data.message,
                                type : 'error',
                                timer : '1500'
                            })
                        }
                    })
                } else {
                swal("Your imaginary file is safe!");
                }
            });
        }
});

This in the head of your page:

<meta name="csrf-token" content="{{ csrf_token() }}">

You can read more on it here: https://laravel.com/docs/5.7/csrf

Hope this helps.

Regards, Ray

Oct
22
11 months ago
Activity icon

Replied to Distinct Not Returning Distinct Results

$builder = order::select('cook_id')->distinct()->orderBy('cook_id')->get();

I'm not sure if this works. But am not sure you need query() and can just use select.

When I use this in my model:

$this->select('year')->distinct()->orderBy('year', 'desc')->get();

I get the desired results.

Activity icon

Replied to Laravel Localhost:8000 Keeps On Loading Without Any Error Or Proper Output

I don't personally use artisan serve. Have used Xampp and if it is running could be causing a conflict.

I would also try running

netstat -an

To see if anything else is running on port 8000 to find a conflict.

Activity icon

Replied to Laravel Localhost:8000 Keeps On Loading Without Any Error Or Proper Output

If they are not there. Share your actual setup. Using Xampp you would put your projects in the htdocs folder and serve them from that directory.

Have you started

php artisan serve

You need to do that to get to localhost:8000

Activity icon

Replied to Distinct Not Returning Distinct Results

$builder = order::query()->select('cook_id')->distinct()->orderBy('cook_id');

Try that and you should get what you're looking for.

Activity icon

Replied to Laravel Localhost:8000 Keeps On Loading Without Any Error Or Proper Output

Alternitivley you could use https://laragon.org/ as your local server and it will automatically setup domains like yourapp.oo in both the HOSTS and httpd.conf file whenever you create a new laravel app.

Activity icon

Replied to Laravel Localhost:8000 Keeps On Loading Without Any Error Or Proper Output

If you're using Xampp it should just be http://localhost without the port.

Sep
06
1 year ago
Activity icon

Replied to How To Change The Default Directory Structure

@Holbi you’re welcome. Thank you for the update info!

Sep
04
1 year ago
Activity icon

Replied to Getting Distinct Data Based On Specific Columns

You need to use orderBy as well.

$this->select('year')
            ->where('condition_id', $cond)
            ->distinct()
            ->orderBy('year', 'desc')
            ->get();

Something like above.

Regards,

Ray

Activity icon

Replied to Hey Guys. I Need Some Ideas. How Can I Use Javascript To Differentiate $ids Of Objects?

Depends on what you want to do. If use something like a dialog / modal, such as a photo modal. Here is how I do it:

Button to open the modal. Notice the data-id="{{ $vehicle->id }}". This will let the modal know the ID for this vehicle.

<button type="button" class="btn btn-pure icon btn-xs btn-dark open-uploadPhotosDialog" data-toggle="modal" data-target="#uploadPhotoModal" data-id="{{ $vehicle->id }}">
    <i class="icon wb-gallery" aria-hidden="true"></i>
</button>

My modal:

<div class="modal fade modal-primary" id="uploadPhotoModal" tabindex="-1" role="dialog" aria-labelledby="uploadPhotosLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content" style="width: 100%;">
            <div class="modal-header">
                <h4 class="modal-title" id="exampleModalLabel">Upload Photos</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="" enctype="multipart/form-data" method="post" class="modal-content" id="uploadPhotosForm">
                {{ csrf_field() }}
                <div class="modal-body">
                    <div class="alert alert-alt alert-info alert-dismissible" role="alert">
                        <strong>This form is meant to process quick uploads. You can upload a MAX of 8 photos here, each
                        photo cannot exceed 3MB</strong>.
                    </div>
                    <div id="file-errors" style="margin-bottom: 10px;"></div>
                    <div id="server-results" style="margin-bottom: 10px;"></div>
                    <input type="hidden" id="vehicleId" name="vehicleId" value="">
                    <div class="file-loading">
                        <input id="input-photos" name="photos[]" multiple type="file">
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

This is where I handle the uploads:

    $("#uploadPhotosForm").submit(function(event){
        event.preventDefault(); //prevent default action
        var post_url = '{{ route('dealer::inventory.upload.photos') }}'; //get form action url
        var request_method = 'POST'; //get form GET/POST method
        var form_data = new FormData(this); //Creates new FormData object
        $.ajax({
            url : post_url,
            type: request_method,
            data : form_data,
            contentType: false,
            cache: false,
            processData:false
        }).done(function(response){ //
            $("#server-results").html(response);
        });
    });
    
    // Clear the vehicleId from the modal once it is closed.
    $("#uploadPhotoModal").on("hidden.bs.modal", function () {
        $('#vehicleId').val('');
    });

There are multiple ways to do this, depending on exactly what you're trying to do. I hope this helps get you in the right direction.

Regards,

Ray

Activity icon

Replied to Laravel 5.2 Different Tokens On Blade And VerifyCsrfToken

You can send the csrf-token via ajax using the following:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

This should verify for each request you send. I use this with v5.5+ and have had no issues.

Hope this helps.

Regards,

Ray

Sep
01
1 year ago
Activity icon

Replied to Role Base Permission Check In Laravel 5.6

Entrust has the same options to check a users permissions. Check the User Ability docs out here: https://github.com/Zizaco/entrust#user-ability

Example usng blade:

@permission('manage-admins')
    <p>This is visible to users with the given permissions. Gets translated to 
    \Entrust::can('manage-admins'). The @can directive is already taken by core 
    laravel authorization package, hence the @permission directive instead.</p>
@endpermission

@ability('admin,owner', 'create-post,edit-user')
    <p>This is visible to users with the given abilities. Gets translated to 
    \Entrust::ability('admin,owner', 'create-post,edit-user')</p>
@endability
Activity icon

Replied to Role Base Permission Check In Laravel 5.6

I would suggest breaking your menu up into separate views. Each view would have only the menu items available for that particular role. For instance:

@if($user->isSuperdmin) 
    @include('menus.superAdmin')
@endif

If you are using Entrust you could do something like so:

@role('superadmin')
    @include('menus.superAdmin')
@endrole

I would suggest in future projects if you like Entrust, using Laratrust. It is actively maintained and has some good features. https://github.com/santigarcor/laratrust

Hope this helps.

Regards,

Ray

Aug
31
1 year ago
Activity icon

Replied to Multi Auth With Roles And Permissions

There are a few packages you could consider or view to get an idea of writing you own.

https://github.com/santigarcor/laratrust

https://github.com/spatie/laravel-permission

https://github.com/JosephSilber/bouncer

I've used the first two and like them both. Hope this helps.

Regards, Ray

Jul
19
1 year ago
Activity icon

Replied to Yajra Datatables With Styled Results

You can use something like this to check and show accordingly:

{ data: 'is_new', name: 'is_new',
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
        var isnew;
        if(oData.is_new == 0){
            isnew = 'Used';
        }else{
           isnew = 'New';
        }
        $(nTd).html(isnew);
   }
}

I check to see if the field is_new is 0 if it is then show Used if not show New.

Hope this helps.

Activity icon

Replied to How To Insert Value In DB (Postgres) From Radio Button Or TextBox.

Here's an example I found by searching google: http://jsfiddle.net/technologrich/tT48f/4/

You can see more results here: https://www.google.com/search?client=firefox-b-1-ab&q=show+textbox+when+radio+button+is+clicked&spell=1&sa=X&ved=0ahUKEwiEgrPlwKrcAhUKGnwKHSV1BaAQBQgmKAA&biw=1536&bih=768

Saving to the DB would by like saving any other field. Do a check to see if textField has something entered, but only if the 4th radio button is clicked.

Jul
09
1 year ago
Activity icon

Replied to Relationship Help

I would do something like this:

Profile model

public function User()
  {
    return $this->belongsTo('App\Models\User');
  }

Another table for the company profile CompanyProfile model

public function Company()
  {
    return $this->belongsTo('App\Models\Company')->with(['Country', 'State', 'City']);
  }

Company model

public function User()
  {
    return $this->belongsToMany('App\Models\User');
  }


    public function Profile()
    {
        return $this->hasOne('App\Models\CompanyProfile');
    }

User model

public function Company()
  {
    return $this->belongsToMany('App\Models\Company');
  }

Pivot table to handle the Company's users Table company_user

Schema::create('team_user', function (Blueprint $table) {
            $table->integer('company_id')->unsigned()->nullable();
            $table->foreign('company_id')->references('id')->on('company')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

Hope this gets you pointed in the right direction.

Regards, Ray

Jul
08
1 year ago
Activity icon

Replied to Help With Getting Data Joined From ONE To MANY With SUM Of Fields

Thank you both for the help. @Tray2 using raw didn't help much but as @staudenmeir stated, adding select into DB::select worked.

Again, thank you both for the help. I spent coutless hours trying to make this work with Eloquent without any success.

Regards, Ray

Activity icon

Replied to Help With Getting Data Joined From ONE To MANY With SUM Of Fields

@Tray2 Thanks for the feedback. Your query appears to be working fine when I run it in HeidiSQL or via command line. However, when I set it up in my controller to test it throws an error.

Here is the way I am running it via HeidiSQL and command line:

select inventories.id, inventories.dealer_id, inventories.stock, inventories.year, inventories.make, sum(vehicle_stats.views) views, sum(vehicle_stats.test_drives) test_drives from inventories left join vehicle_stats on inventories.id = vehicle_stats.inventory_id where inventories.condition_id = 2 and inventories.dealer_id = 1 group by inventories.dealer_id, inventories.id, inventories.stock, inventories.year, inventories.make; 

Here is how it is setup in the controller for testing:

DB::select('inventories.id, inventories.dealer_id, inventories.stock, 
        inventories.year, inventories.make, sum(vehicle_stats.views) views, sum(vehicle_stats.test_drives) test_drives 
        from inventories left join vehicle_stats on inventories.id = vehicle_stats.inventory_id where inventories.condition_id = 2 
        and inventories.dealer_id = 1 group by inventories.dealer_id, inventories.id, inventories.stock, inventories.year, inventories.make');

Error I receive when testing via the controller:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'inventories.id, inventories.dealer_id, inventories.stock, inventories.y' at line 1 (SQL: inventories.id, inventories.dealer_id, inventories.stock, inventories.year, inventories.make, sum(vehicle_stats.views) views, sum(vehicle_stats.test_drives) test_drives from inventories left join vehicle_stats on inventories.id = vehicle_stats.inventory_id where inventories.condition_id = 2 and inventories.dealer_id = 1 group by inventories.dealer_id, inventories.id, inventories.stock, inventories.year, inventories.make)

What am I doing wrong in my controller?

Thank you in advance for your help.

Regards, Ray

Activity icon

Replied to Fresh Install Of Laravel Spark, Registration Page Throws An SQL Error

Odd, did you make any changes to create() in the Auth\RegisterController? Can you post it here?

The error you're getting is telling you the password is not being sent.

Regards, Ray

Activity icon

Replied to Fresh Install Of Laravel Spark, Registration Page Throws An SQL Error

It is because you're not sending a password with the form.

Activity icon

Replied to Using || Operator In PHP

@AlexanderKim if you are always wanting to make sure neither is the URL that is being reached maybe try using && instead.

@if (url()->previous() != Request::root() . '/admin/news' && url()->previous() != Request::root() . '/admin/pages')
true
@endif 

This would return true only if the URL did not equal both of the two conditions. As @Snapey stated the current statement will only be checked against the second condition if you indeed go to /admin/news.

Hope this helps.

Regards, Ray

Activity icon

Replied to Help With Getting Data Joined From ONE To MANY With SUM Of Fields

So in a nutshell there are 348 records in the inventories table and only 41 of them have vehicle_stats data. But I need the data for all 348 records regardless is there is stats data, and the stats data if there is some.

Hope that makes since.

Regards, Ray

Activity icon

Replied to Help With Getting Data Joined From ONE To MANY With SUM Of Fields

@Tray2 thanks for the info, however this did not fix the problem. Once I add ALL fields I want to query and add the GROUP BY for all the fields it will still only return 41 of the items in the inventories table.

This should be returning 348 even if there is nothing in the vehicle_stats table it should still provide the information for the inventory item.

Activity icon

Replied to Relationship Help

I did something similar with teams, in your case a team could be a dealer and have many users. Using a pivot table you can get the relationship between the Company and Users.

Example User model:

/**
  * Get company info for user
  */
public function company()
{
    return $this->belongsToMany('App\Company');
}

Example Company model

/**
  * Get users for company.
  *
  */
public function users()
{
    return $this->belongsToMany('App\User');
}

Pivot Table:

Schema::create('company_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('company_id')->unsigned()->nullable();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

This would allow every user to have a profile and still be attached to a company. You could have a separate company_profiles table just for the companies and associate them with the company that way as well.

Hope this helps get you in the right direction!

Regards, Ray

Activity icon

Started a new conversation Help With Getting Data Joined From ONE To MANY With SUM Of Fields

Hello,

I've been at this for quite some time now and I cannot figure it out and hope I can get some help from someone here. First let me say I am by no means an SQL guru but I try before I ask, problem is I don't understand joins very well and am learning.

Ok now for the issue!

I have a table named 'inventories' with the following fields I need to select:

id,condition_id,stock,year,make.model,trim,vin,slug,created_at

There are other fields in the DB but for this query I only need those.

The other table I am trying to get data from is 'vehicle_stats' with the following fields:

inventory_id,views,quotes,test_drives,credit_apps,friends_referred,payments_calculated,printed,created_at

The relationship is a One to Many, where each inventory can have many vehicle_stats.

Here are the relationships in the models:

Inventory model:

    public function vehicleStats()
    {
        return $this->hasMany('Dbn\Models\Stats\VehicleStat');
    }

VehicleStat model:

public function vehicle()
    {
        return $this->belongsTo('Dbn\Models\Dealer\Inventory');
    }

Each vehicle can HAVE many stats for the same month but only one entry per day. Example:

Query to get the inventories:

$this->dlrInventory
                ->where('dealer_id', Auth::user()->dealer_id)
                ->where('condition_id', 2)
                ->get();

Query to get the total stats for the month and year:

VehicleStat::select(DB::raw('SUM(views) as views,
                                        SUM(quotes) as quotes,
                                        SUM(test_drives) as testDrives,
                                        SUM(credit_apps) as creditApps,
                                        SUM(friends_referred) as friendsReferred,
                                        SUM(payments_calculated) as paymentsCalculated,
                                        SUM(printed) as printed, inventory_id'))
            ->where(DB::raw('MONTH(created_at)'), '=', $month)
            ->where(DB::raw('YEAR(created_at)'), '=', $year)
            ->where('inventory_id', $vehicleId)
            ->groupBy('inventory_id')->first();

If I run the above query using 07 as the month, 2018 as the year, and 16 as inventory_id I would get the following:

$vehicle_stats = array(
    array('views' => 20,
        'quotes' => 20,
        'testDrives' => 18,
        'creditApps' => 23,
        'friendsReferred' => 20,
        'paymentsCalculated' => 19,
        'printed' => 6,
        'inventory_id' => 16,
    ),
);

That would be the combination of two rows of data. Which is the desired results. However I have to run that query for EACH inventory item to get the results.

Both queries work correct on their own, and I can loop through each record when showing them to get the desired results for display. But this is way more server intensive than I think it needs to be and I figure there has to be a better more efficient way.

My combination attempt:

$testInventory = DB::table('inventories')
            ->leftJoin('vehicle_stats', 'inventories.id', '=', 'vehicle_stats.inventory_id')
            ->select(DB::raw('inventories.id, inventories.year'), DB::raw('SUM(vehicle_stats.views) as views,
                                        SUM(vehicle_stats.quotes) as quotes,
                                        SUM(vehicle_stats.test_drives) as testDrives,
                                        SUM(vehicle_stats.credit_apps) as creditApps,
                                        SUM(vehicle_stats.friends_referred) as friendsReferred,
                                        SUM(vehicle_stats.payments_calculated) as paymentsCalculated,
                                        SUM(vehicle_stats.printed) as printed, vehicle_stats.inventory_id'))
            ->where('inventories.dealer_id', Auth::user()->dealer_id)
            ->where('inventories.condition_id', 2)
            ->where(DB::raw('MONTH(vehicle_stats.created_at)'), '=', '07')
            ->where(DB::raw('YEAR(vehicle_stats.created_at)'), '=', '2018')
            ->groupBy('vehicle_stats.inventory_id')->get();

Now if I do the following:

$testInventory = DB::table('inventories')
            ->leftJoin('vehicle_stats', 'inventories.id', '=', 'vehicle_stats.inventory_id')
            ->select(DB::raw('inventories.id'), DB::raw('SUM(vehicle_stats.views) as views,
                                        SUM(vehicle_stats.quotes) as quotes,
                                        SUM(vehicle_stats.test_drives) as testDrives,
                                        SUM(vehicle_stats.credit_apps) as creditApps,
                                        SUM(vehicle_stats.friends_referred) as friendsReferred,
                                        SUM(vehicle_stats.payments_calculated) as paymentsCalculated,
                                        SUM(vehicle_stats.printed) as printed, vehicle_stats.inventory_id'))
            ->where('inventories.dealer_id', Auth::user()->dealer_id)
            ->where('inventories.condition_id', 2)
            ->where(DB::raw('MONTH(vehicle_stats.created_at)'), '=', '07')
            ->where(DB::raw('YEAR(vehicle_stats.created_at)'), '=', '2018')
            ->groupBy('vehicle_stats.inventory_id')
            ->groupBy('inventories.id')->get();

I get some of the results, but definitely not all. There should be 349 inventory items. Here is what I get with the above query:

Collection {#1393 ▼
  #items: array:9 [▼
    0 => {#1330 ▼
      +"id": 6
      +"views": "4"
      +"quotes": "8"
      +"testDrives": "10"
      +"creditApps": "0"
      +"friendsReferred": "6"
      +"paymentsCalculated": "9"
      +"printed": "2"
      +"inventory_id": 6
    }
    1 => {#1331 ▼
      +"id": 10
      +"views": "0"
      +"quotes": "10"
      +"testDrives": "14"
      +"creditApps": "0"
      +"friendsReferred": "10"
      +"paymentsCalculated": "10"
      +"printed": "1"
      +"inventory_id": 10
    }
    2 => {#1332 ▶}
    3 => {#1333 ▶}
    4 => {#1334 ▶}
    5 => {#1335 ▶}
    6 => {#1336 ▶}
    7 => {#1337 ▶}
    8 => {#1338 ▶}
  ]
}

If I add anything to the select method I get a GROUP BY error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'dbnmaindb.inventories.year' isn't in GROUP BY (SQL: select inventories.id, inventories.year, SUM(vehicle_stats.views) as views,\n ◀
                                        SUM(vehicle_stats.quotes) as quotes,\n
                                        SUM(vehicle_stats.test_drives) as testDrives,\n
                                        SUM(vehicle_stats.credit_apps) as creditApps,\n
                                        SUM(vehicle_stats.friends_referred) as friendsReferred,\n
                                        SUM(vehicle_stats.payments_calculated) as paymentsCalculated,\n
                                        SUM(vehicle_stats.printed) as printed, vehicle_stats.inventory_id from `inventories` left join `vehicle_stats` on `inventories`.`id` = `vehicle_stats`.`inventory_id` where `inventories`.`dealer_id` = 1 and `inventories`.`condition_id` = 2 and MONTH(vehicle_stats.created_at) = 07 and YEAR(vehicle_stats.created_at) = 2018 group by `vehicle_stats`.`inventory_id`, `inventories`.`id`)

Excuse the very long post, but I wanted to be as detailed as possible. I hope this makes since and someone can help me out.

Best Regards, Ray

Oct
07
2 years ago
Activity icon

Replied to Installing Laravel And Welcome Page

I would suggest using something like laragon which will create virtual hosts for you.

https://laragon.org

So you address would be http://eliteshop.dev

That is if you're not familiar with setting up virtual hosts on your machine.

Sep
07
2 years ago
Activity icon

Replied to Generating PDFs From Laravel Views

@Sofia This package will generate a PDF file and you would be able to copy and paste contents in the generated PDF file.

I have used it to generate invoices from views and it has worked very well. Works good for combining PDFfiles also.

https://github.com/barryvdh/laravel-dompdf

Hope this helps.

Sep
01
2 years ago
Activity icon

Replied to Problem In Route

Maybe you have a clash with another Route for this one. I am assuming these routes are in a group with a prefix?

Can you post your routes file or at least the group?

Activity icon

Replied to Problem In Route

What server are you running locally?

It appears that your base localhost is pointing to directory site which would be why the route is sending you to localhost/quiz

You need to point localhost to the directory above site locally.

Aug
31
2 years ago
Activity icon

Replied to Updating Value

Couldn't you use the increment and decrement to accomplish this?

// Would increase the value by 12
$artikli->increment('quantity', $request->input('quantity'));

// Increase by 1
$artikli->increment('quantity');

// Would decrease the value by 12
$artikli->decrement('quantity', $request->input('quantity'));

// Decrease by one
$artikli->decrement('quantity');


// Borrowed from above post
//Function in article controller to update the quantity
public function updateQuantity(Request $request,$id){
    $artikli =  Artikl::find($id);
    $artikli->increment('quantity', $request->input('quantity'));
    $artikli->save();
    return back();
}

Reference: https://laravel.com/docs/5.4/queries#increment-and-decrement

Aug
30
2 years ago
Activity icon

Replied to How Can I Solve Target [App\Repositories\NewsRepository] Is Not Instantiable While Building [App\Http\Controllers\Member\NewsController].?

I'm not familiar with the package you're using but here is an example of an implementation I have used:

NewsRepository

namespace App\Repositories;

use App\News;

class NewsRepository implements NewsRepositoryInterface
{

    public function all()
    {
        return News::all();
    }

    public function create($data)
    {
        return News::create($data);
    }

    public function find($id)
    {
        return News::find($id);
    }

    public function delete($id)
    {
        return News::destroy($id);
    }

    public function update($id, array $data)
    {
        return News::find($id)->update($data);
    }
}

NewsRepositoryInterface

namespace App\Repositories;

interface NewsRepositoryInterface
{

    public function all();

    public function create($data);

    public function find($id);

    public function delete($id);

    public function update($id, array $data);
}

Then in your service provider:


namespace App\Repositories;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{


    public function register()
    {
        $this->app->bind(
            'App\Repositories\NewsRepositoryInterface',
            'App\Repositories\NewsRepository');
    }
}

Add this to your config/app.php:

App\Repositories\RepositoryServiceProvider::class,

In your controller

use App\Repositories\NewsRepositoryInterface;

class NewsController extends Controller
{
    protected $repository;

    public function __construct(NewsRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function store(NewsCreateRequest $request)
    {
        $news = $this->repository->create($input);
    }
}

Hope this helps.

Activity icon

Replied to How Can I Solve Target [App\Repositories\NewsRepository] Is Not Instantiable While Building [App\Http\Controllers\Member\NewsController].?

If i'm not mistaken you need to add this to your interface:

public function store(NewsCreateRequest $request);
Activity icon

Replied to Help With Relatonships One To Many With Pivot Table And One To One For Team

For now I modified myteam to only retrieve the first record and this works.

public function myTeam()
{
    return $this->belongsToMany('App\Team')->first();
}

Still curious as to if there is a better way.

Activity icon

Started a new conversation Help With Relatonships One To Many With Pivot Table And One To One For Team

It's quite possibly I am overthinking this and just can't see the answer. I hope someone can point me in the right direction as to how I can accomplish this task.

Basically I have the normal users table with the auto increment id

I also have a teams table setup like:

id
manager_id // This user id is the teams lead (manager)
team_name
team_description

I have a pivot table named team_user

id
team_id
user_id

I have the relationship for the manager setup like so:

// Team model
public function manager()
    {
        return $this->belongsTo('App\User', 'manager_id');
    }

public function users()
    {
        return $this->belongsToMany('App\User');
    }

User model

public function team()
    {
        return $this->hasOne('App\Team', 'manager_id');
    }

public function myteam()
    {
        return $this->belongsToMany('App\Team');
    }

Which is working fine. And I know I can get the team by using:

$user->myteam->first();

Now each user can only belong to ONE team. Each team can have Many Users. The team only has One team lead (manager).

I am trying to avoid adding a team_id column to the users table and use the pivot table instead.

However, is there a way to have the user only associated with ONE team using the pivot table?

Is there an easy way to achieve this? Any suggestions would be greatly appreciated.

Edit: Added the current relationships.

Aug
29
2 years ago
Activity icon

Replied to Controller Functions

You could use an if statement to test for the admin

// Check if the user has admin role or not
if(Auth::user()->is_admin) {

    //THIS FUNCTION MUST ADD CATEGORIES IN MY ADMIN
    $categories=Category::orderBy('name')->paginate(5);
      return view('admin.categories.index', compact('categories'));

}else{

    $postsPerPage = 10; //As many posts as you want to show on each page
    $posts = $category->posts()->paginate($postsPerPage);
     return view('front.blog', compact('posts'));

}

But as others have said why not have a controller for your admin and another for home.

Aug
26
2 years ago
Activity icon

Replied to If And Isset Usage In Laravel 5.4

@JackJones is right. There is no need for the @if statement in this loop.

On a different note using isset() will return true of the variable exists and is empty. If your intended use it to check that something is in the variable you should use:

@if(!empty($variable))
    // Doe something if there is a value
@endif

Aug
24
2 years ago
Activity icon

Replied to Storage Folder Upon Deploy

I'm not sure why this happens and I am new to forge but maybe have the command you issue to unlock it run in the Deploy script?

Under Sites->yoursite then under Deploy Script maybe add the code you want run after whats there and save it.

Haven't tried it but in theory I think it would work.

Aug
20
2 years ago
Activity icon

Replied to Integrity Constraint Violation: 1048 Column 'job_id' Cannot Be Null

Have you tried using sync() instead of attach?

$model->job_category()->sync($data['categories']);

This is assuming $data['categories'] is an array of ID's.

Activity icon

Replied to How To Make A Shopping Cart With Laravel?

I did a Google search on 'How to make a shopping cart with laravel' came up with a few examples:

Here's a repo that has one: https://github.com/Crinsane/LaravelShoppingcart

Another discussion about it here: https://laracasts.com/discuss/channels/general-discussion/simple-shopping-cart

Here's a YouTube video on creating one: https://www.youtube.com/watch?v=oc1_DHfL89k

Stripe integration tutorial can be found here: http://justlaravel.com/integrate-stripe-payment-gateway-laravel/

And here for subscriptions (I tested this one with v5.4 and it worked pretty good): http://www.qcode.in/subscription-with-coupon-using-laravel-cashier-stripe/

Didn't watch the video but hope those give you a good start.

Activity icon

Replied to Integrity Constraint Violation: 1048 Column 'job_id' Cannot Be Null

Where is the job_id? In your data you are not passing a job_id to attach.

You should change your method names to be more descriptive as well as the variables.

Is getModel() for the category or the Job?

Aug
19
2 years ago
Activity icon

Replied to Using Jeff's Filters

@Cronix you're right. Was replying from my phone and not thinking it through completly.

Wanted to point the op in the right direction.

Regards, Ray