Monday, April 30, 2018

Laravel 5.2 Login With Condition - development

Laravel 5.2 Login With Condition

So, I have users table which is default by laravel. But I add a new column named ‘status’.

So the columns on the users table are id, name, email, password, remember_token, created_at, updated_at, status

The status values are between 0 and 1. 1 for admin, and 0 for regular user.

Also I have auth, but the problem is how can I check if users’ status is 0 or 1 when login so that I can redirect it according to their status? — admin will go to admin panel and user will go to home

User default by laravel with addition ‘status’

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

    class User extends Authenticatable
    {
        use Notifiable;
        protected $fillable = [
            'name', 'email', 'password', 'status',
        ];
        protected $hidden = [
            'password', 'remember_token',
        ];
    }

HomeController also default by laravel

use IlluminateHttpRequest;

class HomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }
}

LoginController also default by laravel

use AppHttpControllersController;
use IlluminateFoundationAuthAuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/home';

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

THANKS.



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-5-2-login-with-condition/
via Lzo Media

Laravel testing (sitemap xml page) ->get() returns blank xml - development

Laravel testing (sitemap xml page) ->get() returns blank xml

I’m trying to test a Laravel sitemap page.

Want to test that a uri ‘sitemap/departments.xml’ contains ‘/adhesives-sealants/adhesives/c657’

Here is my code:

    $response = $this->get( 'sitemap/departments.xml');

    $response->assertSee('/adhesives-sealants/adhesives/c657');

This is the response I get from test:

   Failed asserting that '' contains "/interior-exterior-pva-wood-glue/p31670".

When I dump out $response I get this:

<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  </urlset>

Which is not what is on the page!

Page looks like this

enter image description here

Where am i going wrong???



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-testing-sitemap-xml-page-get-returns-blank-xml/
via Lzo Media

Multi option filter from selection in laravel - development

Multi option filter from selection in laravel

I have a search form to filter out accounts to show their transactions using relations. I have it working to filter a single account. I need to create the filter multiple accounts together. Here is my code for filtering a single selection since I am ne to Laravel< I am getting stuck. Thanks in advance.

   public $relations = [];
public function account($account)
{ 
       return $this->where('account_id', $account);
}   }



from Laravel Questions and Answers https://laravelquestions.com/php/multi-option-filter-from-selection-in-laravel/
via Lzo Media

Idle DEALLOCATE queries in postgresql laravel - development

Idle DEALLOCATE queries in postgresql laravel

In Laravel 5.6 after turning on schedule Cronjob suddenly many idle queries apears on htop

What do this to Postgresql in a Laravel Application?

Htop:

enter image description here



from Laravel Questions and Answers https://laravelquestions.com/laravel/idle-deallocate-queries-in-postgresql-laravel/
via Lzo Media

Pass id parameter to resource in Laravel - development

Pass id parameter to resource in Laravel

I have the following method in my Laravel controller:

public function specialOffers($id) {
    return AppHttpResourcesSpecialOfferResource::collection(Offers::all());
}

I need some special manipulations, so I’ve created this SpecialOfferResource resource. The resource code is:

class SpecialOfferResource extends Resource {
    /**
     * Transform the resource into an array.
     *
     * @param  IlluminateHttpRequest $request
     * @return array
     */
    public function toArray($request) {

        //here I need the $id passed to the controller's method,
        //but I only have $request

        return [
            //my request fields, everything ok
        ];

    }
}

How can I pass $id from the controller’s method to this resource? I know I can pass through the request as a field, but is it possible this other way?



from Laravel Questions and Answers https://laravelquestions.com/php/pass-id-parameter-to-resource-in-laravel/
via Lzo Media

Get textarea Info Value LARAVEL - development

Get textarea Info Value LARAVEL

How get value / info in LARAVEL?

admin.blade.php: https://pastebin.com/XHMM3PN9

GeneralController.php

$socket = $_POST['compr'];

ROUTE:

Route::post('sname', 'GeneralController@Sname')->middleware(['auth','admin:6']);



from Laravel Questions and Answers https://laravelquestions.com/laravel/get-textarea-info-value-laravel/
via Lzo Media

Run Supervisor on CloudFoundry - development

Run Supervisor on CloudFoundry

Is there a way to install an run Supervisor in the php-buildpack of CloudFoundry?

I have a Laravel app and wan’t some monitored background processes to work on queued jobs.

I can install supervisor with the apt-buildpack, but when ever i wan’t to start supervisor with supervisord -c supervisord.conf i get the following error:

Traceback (most recent call last):
File "/home/vcap/deps/0/bin/supervisorctl", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

This is my supervisord.conf:

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/vcap/app/artisan queue:work --tries=3
autostart=true
autorestart=true
user=vcap
numprocs=2
redirect_stderr=true
stdout_logfile=/home/vcap/app/storage/logs/worker.log



from Laravel Questions and Answers https://laravelquestions.com/laravel/run-supervisor-on-cloudfoundry/
via Lzo Media

Laravel’s Passport: How to have an authenticatable model - development

Laravel’s Passport: How to have an authenticatable model

The problem with the Laravel’s Passport tutorial is that it assumes the reader will use the pre-installed User model, that is very different from the simple model we could create with php artisan make:model MyModel.

Here is the code of the pre-installed User model:

<?php
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

And here is the code of a model you could create with php artisan make:model MyModel:

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class MyModel extends Model
{

}

But what if I want my own custom authenticatable models, say Customer, what should I do to follow the Passport tutorial? Is there an Artisan command that implements all the interfaces, add all the traits and extend the corresponding class for us?

Thank you for your help.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravels-passport-how-to-have-an-authenticatable-model/
via Lzo Media

Laravel 5.6.18 Released - development

Laravel 5.6.18 Released

Laravel 5.6.18 was released on Friday with added support for MySQL 8 compatibility, support for custom filesystem driver URLs, more PostgreSQL operators, and added support for JSONP callbacks when broadcasting to Pusher. Learn about the newest release of Laravel 5.6.

Visit Laravel News for the full post.

The post Laravel 5.6.18 Released appeared first on Laravel News.



from Laravel Questions and Answers https://laravelquestions.com/news/laravel-5-6-18-released/
via Lzo Media

In laravel data is not inserting into database - development

In laravel data is not inserting into database

I am new to laravel and doing project using laravel framework please help me to solve this problem.

data is not inserting into table.

routes.php

Route::post('report/save','TestingController@store');

TestingController

 public function store(Request $request){
        $userId = Auth::user()->id;
        $this->validate($request, [
            'from_stk_loc' => 'required',
            'testing_date' => 'required',
            'casting_date' => 'required',
            'debtor_no' => 'required',
            'concrete_grade' => 'required',
            'testing_age' => 'required',
        ]);

        $test_details['client_id'] = $request->debtor_no;
        $test_details['location'] = $request->from_stk_loc;
        $test_details['casting_date'] = $request->casting_date;
        $test_details['testing_date'] = $request->testing_date;
        $test_details['concrete_grade'] = $request->concrete_grade;
        $test_details['testing_age'] = $request->testing_age;
        $test_details['report_date'] = date('Y-m-d');

        $test_detailsId = DB::table('testing_report')->insert($test_details);


    }

Model-> Testing.php

<?php

namespace AppModel;
use DB;
use IlluminateDatabaseEloquentModel;

class Testing extends Model
{
    protected $table = 'testing_report';
    protected $fillable = [
    'client_id',
    'location',
    'casting_date',
    'testing_date',
    'concrete_grade',
    'testing_age',
];
}



from Laravel Questions and Answers https://laravelquestions.com/laravel/in-laravel-data-is-not-inserting-into-database/
via Lzo Media

Friday, April 27, 2018

spatie/laravel-server-side-rendering - development

spatie/laravel-server-side-rendering
Server side rendering JavaScript in your Laravel application



from Laravel Questions and Answers https://laravelquestions.com/laravel-packages/spatie-laravel-server-side-rendering/
via Lzo Media

Apache 2.4 – Request exceeded the limit of 100 internal redirects due to probable configuration error - development

Apache 2.4 – Request exceeded the limit of 100 internal redirects due to probable configuration error

I’m running Apache 2.4 (64bit) and PHP 7.1 on windows Server 2008 R2 Enterprise and have noticed the following error in the Apache error log which produces a HTTP error 500 on all pages except the home page:

AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I think the error is coming from an error in the htaccess rewrites and I have looked at a similar posts but have been unable to dettermine which strategy to follow. Here’s a sample of my .htaccess public domain:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

The error came out of all of a sudden and while I’m able to access my-site.com, I cannot access any of my-site.com/page.
Can anyone suggest what I need to change?



from Laravel Questions and Answers https://laravelquestions.com/laravel/apache-2-4-request-exceeded-the-limit-of-100-internal-redirects-due-to-probable-configuration-error/
via Lzo Media

How to control the html elements with Vue and Laravel? - development

How to control the html elements with Vue and Laravel?

I have 2 basic files in order to manage the html in the page. The Vue component and the blade file. My blade file looks like this

@section('content')
    <products-component></products-component>
    <div class="row">
        <div class="mx-auto"></div>
        <div class="row">
            @foreach ($products as $product)
                <div class="col-md-4">
                    <div class="card mb-4 box-shadow">
                        <img src="/images/products///" class="card-img-top" alt="" style="height: 225px; width: 100%; display: block;">
                        <div class="card-body">
                            <h3></h3>
                            <p class="card-text"></p>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-outline-secondary">View</button>
                                    <button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
                                </div>
                                <small class="text-muted"></small>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
        <div class="mx-auto"></div>
    </div>
@endsection

and my Vue component html section looks like this

<template>
    <div class="row">
        <input class="form-control" type="search" placeholder="Search" aria-label="Search" v-model="searchKey">
        <div class="col-md-4" v-for="product in products">
            <div class="card mb-4 box-shadow">
                <img :src="'/images/products/' + product.user_id + '/' + product.id + '/' + product.images[0].name" class="card-img-top" :alt="product.name" style="height: 225px; width: 100%; display: block;">
                <div class="card-body">
                    <h3 v-text="product.name"></h3>
                    <p class="card-text" v-text="product.description"></p>
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-outline-secondary">View</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary">Edit</button>
                        </div>
                        <small class="text-muted" v-text="product.created_at"></small>
                    </div>
                </div>
            </div>
        </div>
        <div class="clearfix"></div>
    </div>
</template>

I want to accomplish a couple of things.

  1. How can I manage the search behaviour from the blade file. What ever I put some html content from the Vue component to the blade file it gives me an error saying it didn’t know about the value of the JS I want to use. For example if i put the search bar in the blade file, this part:

It gives me an error: Property or method "searchKey" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Which means the blade file have no clue what is going on inside the Vue component.

  1. I also want when someone search for a product to hide all the html from the blade file and just render the html from the Vue component. I tried doing this with an if-else code inside the blade file, but again it says that the blade file have no clue of if-else’s and what I am trying to do.

I am new to Laraval+Vue so I will be very happy if you can give me a hand and tell me how i suppose to do this. Thanks!

UPDATE: I forgot to mention that after my body tag i have a div with an ID of app and in my app.js file I have this code

const app = new Vue({
    el: '#app'
});

So view can control the html of my code. And it is also working when I am searching for a product, but I can’t make it hide the code from the blade file.

I am using Laravel 5.6 and Vue 2.5.16



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-control-the-html-elements-with-vue-and-laravel/
via Lzo Media

Laravel, Ajax and BS3 dismissable Alerts - development

Laravel, Ajax and BS3 dismissable Alerts

How can I intercept when an alert was dismissed (data-dismiss=alert button) and, with ajax, set status = 0 in my notification model.

I use Laraval 5.5 and Bootstrap 3.
This is the button that I use for dismiss alerts:

<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times"></i></button>



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-ajax-and-bs3-dismissable-alerts/
via Lzo Media

date_format() expects parameter 1 to be DateTimeInterface, null given (View: /home/vagrant/code/blog/resources/views/singlePost.blade.php) - development

date_format() expects parameter 1 to be DateTimeInterface, null given (View: /home/vagrant/code/blog/resources/views/singlePost.blade.php)

i cant find whats wrong with my code.I have tried looking at the whole code but i cant put my finger on it. it would be really helpful if someone pointed out my mistake. it is saying that something is wrong with the date but i cant see what i typed wrong

@extends('layouts.master')
@section('content')

    <!-- Page Header -->
    <header class="masthead" style="background-image: url('')">
      <div class="overlay"></div>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            <div class="post-heading">
              <h1></h1>
              <span class="meta">Posted by
                <a href="#"></a>
                on </span>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- Post Content -->
    <article>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            {!!nl2br($post->content)!!}
          </div>
        </div>
<div class="comments">
  <hr>
  <h2>Comments</h2>
  <hr>
  @foreach($post->comments as $comment)
  <p> <br>
  <p><small>by , on </small></p>
  <hr>
  @endforeach

@if(Auth::check())
<form action="" method="POST">
  @csrf
  <div class="form-group">
<textarea class="form-control" placeholder="Comment..." name="comment" id="" cols="30" rows="4"></textarea>
<input type="hidden" name="post" value="">
</div>
<div class="form-group">
  <button class ="btn btn-primary" type="submit">Make Comment</button>
</div>
</form>
@endif

</div>
</article>
    @endsection


comments.blade.php code



from Laravel Questions and Answers https://laravelquestions.com/php/date_format-expects-parameter-1-to-be-datetimeinterface-null-given-view-home-vagrant-code-blog-resources-views-singlepost-blade-php/
via Lzo Media

How to redirect users to another page with session messages while error occuring - development

How to redirect users to another page with session messages while error occuring

I want to redirect users to admin page when any error occuring about the thujohn/twitter package. It throws Runtimeexception..

So I add couple code handler.php

public function render($request, Exception $exception)
{

    if ($exception instanceof RuntimeException) {
        return redirect()->route('admin.panel')
            ->with('message', 'Please try again later..')
            ->with('message_type','warning');

    } else {
        return parent::render($request, $exception);
    }
}

But when I say that, it redirects user at all exceptions even at 404 errors or Trying to get property of non-object erros.. How can I fix this ? I want to redirect user for just relevant error

Or is there any way to do redirect user with condition like below.

if($exception->code == 436){
  // it says member has protected access. I can't use it code property outside of the exception class
      return redirect()->route('admin.panel')
            ->with('message', 'Specific error message')
            ->with('message_type','warning');

 }



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-redirect-users-to-another-page-with-session-messages-while-error-occuring/
via Lzo Media

Has many: display regions with 1 or more elements - development

Has many: display regions with 1 or more elements

I have relationship between adv and region model. Actually I want to display all regions which has one or more active adv (I have active column into adv). And next similar problem. All regions contain cities. When user choose some region into view he saw all cities from this region. What is the best way to do that?

I won’t write manually every cities. I have 2 ideas:

  1. first cities will be string column. Actually user will choose region and write name of city into input field.

  2. controller will check that this city exist with this region. If not, it’ll create a new.

I think that second idea is better because create search engine and filter results will be simpler.



from Laravel Questions and Answers https://laravelquestions.com/laravel/has-many-display-regions-with-1-or-more-elements/
via Lzo Media

How to send email without enabling "Access for less secure apps" - development

How to send email without enabling "Access for less secure apps"

In my mail configurations:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example@gmail.com
MAIL_PASSWORD=lol
MAIL_ENCRYPTION=tls

But my testing email was enabled for “access for less secure apps”. Is there a chance to send email to any types of email? Currently i can’t get a server email and they configuration. I need to create my own email and integrate to the website.

My searches gives me “2-step verification”. Is system can automatically send mails If i enabled this? I can’t get any solution. I hope somebody can help me. Thanks in advance.



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-send-email-without-enabling-access-for-less-secure-apps/
via Lzo Media

Laravel Nexmo message for response status - development

Laravel Nexmo message for response status

I’m working on an implementation of Nexmo in Laravel using facade.
I want to show a message with the send status (or any response of failure), and the remaining balance in my Nexmo.

Nexmo::message()->'to'=>''from'=>''please check and help`

How can I achieve this?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-nexmo-message-for-response-status/
via Lzo Media

Ajax 405 error and laravel MethodNotAllowedHttpException - development

Ajax 405 error and laravel MethodNotAllowedHttpException

I’m learning laravel now, and I need to know how to update database by AJAX, but I have a problem. When i click button i show on console 405 erorr and next laravel MethodNotAllowedHttpException. But database is updated after this. What’s wrong?

My .js:

var postId = 0;
jQuery.support.cors = true;

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

$('.post').find('.interaction').find('.edit').on('click', function(event) {
    event.preventDefault();

    var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
    postId = event.target.parentNode.parentNode.dataset['postid'];
    $('#post-body').val(postBody);
});

$('#modal-save').on('click', function() {
    $.ajax({
        method: 'post',
        type: 'post',
        url: url,
        data: {body: $('#post-body').val(), postId: postId, _token: token}
    }).done(function (msg) {
        console.log(msg);
    });
});

my route:

Route::post('/update', [
        'uses' => 'PostController@update',
        'as' => 'post.update',
    ]);

and controller:

public function update(Request $request){

        $this->validate($request, [
            'body' => 'required'
        ]);
        $post = Post::find($request['postId']);
        if (Auth::user() != $post->user) {
            return redirect()->back();
        }
        $post->body = $request['body'];
        $post->update();
        return response()->json(['message' => $post->body], 200);
    }

//Edit

I try to change url to ‘/update’ but it’s the same, database is updated, but i see a laravel error.



from Laravel Questions and Answers https://laravelquestions.com/php/ajax-405-error-and-laravel-methodnotallowedhttpexception/
via Lzo Media

Thursday, April 26, 2018

How to deploy Laravel to Kubernetes - development

How to deploy Laravel to Kubernetes

How to deploy Laravel to Kubernetes submitted by /u/keithmifsud
[link] [comments]


from Laravel Questions and Answers https://laravelquestions.com/rlaravel/how-to-deploy-laravel-to-kubernetes/
via Lzo Media

Larave 4.2 cache not putting data - development

Larave 4.2 cache not putting data

I am working in laraval v4.2 and I want to put an array into cache but when I get data from cache then it return false all the time and cache has no data. Below is my working code

$posts = array(
     [0] => 2365
     [1] => 2366
     [2] => 2367
     [3] => 2368
     [4] => 2369
);

$time = 60;

Cache::put('views-87',$posts,$time);

$data = self::getPostsFromCache('views-87');

public static function getPostsFromCache($key){
     if(Cache::has($key)){
          return Cache::get($key);
     }
     return array();
}

Result

empty Array()

Kindly guide in right direction



from Laravel Questions and Answers https://laravelquestions.com/laravel/larave-4-2-cache-not-putting-data/
via Lzo Media

How to set append variable on condition in laravel model? - development

How to set append variable on condition in laravel model?

I am doing project in Laravel. I have model named ‘User.php’ and here I want to set $appends variable depends on condition.

user.php looks like

class User extends Authenticatable
{
protected $appends = ['avatar_photo'];

public function profile_attributes()
    {
        //return $this->hasMany(AppModelsAccessUserUserProfile::class);
        return $this->belongsToMany(AppModelsAccessUserUserProfileAttributes::class,config('access.user_attribute_values_table'),'user_id','user_attribute_id')->withPivot('value', 'active')->withTimestamps();
    }

/**
     * @return string
     */
    public function getAvatarPhotoAttribute()
    {
        $avatar = $this->profile_attributes()->where('user_attributes_master.id',7)->first()->avatar_path;
        return $avatar;

    }
}

Here I get avatar_path attribute to every record which is append variable I have set to profile.php model. How to get this to only ‘avatar’ col of profile.php. How can I set this appends variable.



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-set-append-variable-on-condition-in-laravel-model/
via Lzo Media

Login and register link not working in Laravel after executing make:auth command - development

Login and register link not working in Laravel after executing make:auth command

I have installed laravel in windows and tried the make:auth command to scaffold basic login,registration views and routes. But when i tried to access the page with the url http://127.0.0.1:8000/login, it displayed the following error “Sorry, the page you are looking for could not be found.” I tried searching for the reason. But i didnt get a proper solution yet for the past week. CLICK HERE TO SEE THE login page after running make:auth command



from Laravel Questions and Answers https://laravelquestions.com/laravel/login-and-register-link-not-working-in-laravel-after-executing-makeauth-command/
via Lzo Media

Query builder with 4 tables [duplicate] - development

Query builder with 4 tables [duplicate]

This question already has an answer here:

This is my query builder function :

public function MonthSoldGDV($dev,$year){

            $monthlyGDV = DB::table('pams_unit')
            ->join('pams_phase','pams_unit.phase_id','pams_phase.phase_id')
            ->join('pams_project','pams_phase.project_id','pams_project.project_id')
            ->join('pams_developer','pams_project.dev_id ','pams_developer.id')
            ->select('pams_developer.developer_name')
            ->selectRaw('year(pams_unit.sold_date) as year')
            ->selectRaw('month(pams_unit.sold_date) as month')
            ->selectRaw('sum(pams_unit.sold_price) as gdv')
            ->where('pams_developer.developer_name','$dev')
            ->whereRaw('year(sold_date) = $year')
            ->groupBy('month')
            ->get();

            return $monthlyGDV;

        }

But it show an error Column not found: 1054 Unknown column '$year' in 'where clause'

Can someone help me to figure out my problem ?



from Laravel Questions and Answers https://laravelquestions.com/php/query-builder-with-4-tables-duplicate/
via Lzo Media

Unable to do laravel relationships using laravel 5.5 - development

Unable to do laravel relationships using laravel 5.5

I am facing issue regarding storing ids and display their values from two different table i have 1 table business_master and other table is page_master i have combine business_name column with page_url column which are available on page_master table if i add my business and page first time its successfully combine these two values as one business can have many pages and if i only add page 2nd time i am unable to see business_url with page_url column.

My Page Model:

class PageList extends Model
      {
protected $table = 'page_master';


protected $fillable = ['business_id', 'page_url', 'page_name'];


public function business()
{
    return $this->hasOne('AppBusiness','business_id');
}

   }

and in my view:

 <td>.spikesales.io/</td>

This is my first time out if i add business_url and page_url

    hussain.spikesales.io/house

and then if i add only page the out put is something like that

   .spikesales.io/hello

one business can have many page it should attach business_ url also but i am unable to find solution:

Any help will be highly appreciated!

    public function pageListHere()
{
    $list = PageList::all();
    return view('page-list',compact('list'));
}



from Laravel Questions and Answers https://laravelquestions.com/php/unable-to-do-laravel-relationships-using-laravel-5-5/
via Lzo Media

how can I send one query result (via variable) into an other query - development

how can I send one query result (via variable) into an other query

What I want is to include the result of sub variable into another query.

 $sub = DB::table('chef_food_ethics')->
 select(DB::raw('count(id) as fCount'))
 ->where('chef_food_ethics.food_ethic_id',
 '=','food_ethic_managers.food_ethic_id')
 ->toSql();

Is it possible to include it like that?

 $r = DB::table('food_ethic_managers')where
 ('food_ethic_managers.manager_id','=',$id)
 ->leftJoin('staff','food_ethic_managers.food_ethic_id'
  ,'=','staff.id')
 ->leftJoin('regions','staff.region_id','=','regions.id')
 ->with($sub)
 ->get();



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-can-i-send-one-query-result-via-variable-into-an-other-query/
via Lzo Media

Laravel Throws SQLite error when I change from local Homestead to prod in AWS - development

Laravel Throws SQLite error when I change from local Homestead to prod in AWS

I have created an application that uses the Archon library for creating and manipulating dataframes, here’s the link(Great Library btw!).

The application will create a large array that contains duplicates. I am using the dataframe functionality of Archon to perform a groupBy operation, so that I get the count of each unique entry to the array.

This array varies from being a couple of hundred entries, to many thousand.

Locally, this works fine. I’m using Vagrant, with VirtualBox – and I have a Homestead Box running there. It is running on an Ubuntu 64 bit system.
I’ve recently deployed my application to an elastic beanstalk instance, and this is running on 64bit Amazon Linux/2.6.6.

After deploying, I’m receiving the error of

SQLSTATE[HY000]: General error: 1 too many SQL variables

So it seems like for some reason, after changing systems, the client interacts with the SQLite driver that Archon is built on differently. I’m at a loss as to why this would work locally, but not after deployment.

Here’s the code I’m using which produces the error:

$df = DataFrame::fromArray($batch_array);
$senders_emails = $df->query("SELECT a,sum(b) AS bFROM dataframe GROUP BY 1ORDER BY 2 DESC")->toArray();

Does anyone understand SQLite/Archon/Homestead vs EB well enough to help?
Would greatly appreciate!



from Laravel Questions and Answers https://laravelquestions.com/php/laravel-throws-sqlite-error-when-i-change-from-local-homestead-to-prod-in-aws/
via Lzo Media

laravel ajax query showing undefined before refreshing - development

laravel ajax query showing undefined before refreshing

These are my databases, where a division can have many districts (division_id is the foreign key in districts table).

division
district

When I submit the modal (using Ajax with laravel) the division name comes as undefined.

undefined value

However, after I refresh the browser, everything seems to be working okay. Why is this happening and how do I fix it?

undefined value gone after refreshing

This is the code I am using to show the data.


<?php  $no=1; ?>
@foreach ($district as $district)
<tr class="post">
    <td></td>
        <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
        <a href="#" class="show-modal btn btn-info btn-sm" data-id="" data-division_id="" data-code="" data-name="" >
            <i class="fa fa-eye"></i>
        </a>
        <a href="#" class="edit-modal btn btn-warning btn-sm"  data-id="" data-division_id="" data-code="" data-name="" >
            <i class="glyphicon glyphicon-pencil"></i>
        </a>
        <a href="#" class="delete-modal btn btn-danger btn-sm" data-id="" data-division_id="" data-code="" data-name="" >
            <i class="glyphicon glyphicon-trash"></i>
        </a>
    </td>
</tr>
@endforeach

This is my controller.

use IlluminateHttpRequest;
use AppDivision;
use AppDistrict;
use Validator;
use Response;
use IlluminateSupportFacadesInput;
use ApphttpRequests;

class DistrictController extends Controller
{
    public function index()

    {   $district = District::all();
        $divisionDistricts = Division::pluck('name','id');
        return view('masterForms.district',compact('district','divisionDistricts'));
    }

    public function store(Request $request)
    {
        if($request->ajax())
        {
            $district = District::create($request->all());
             $district->save();
            return response($district);
        }
     }

This is my District Model.

<?php

namespace App;

use IlluminateDatabaseEloquentModel;
use AppDivision;

class District extends Model
{
    protected $fillable = ['code','name','division_id'];

    public function division()
    {
        return $this->belongsTo(Division::class);
    }
}

?>

And this is the javaquery I am using to add my data to the database.

<script type="text/javascript">
    $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
    }
});
    $(document).on('click','.create-modal', function() {
        $('#create').modal('show');
        $('.form-horizontal').show();
        $('.modal-title').text('Add District');
    });
    $('#ddistrict').on('submit',function(e){
        e.preventDefault();
        var data = $(this).serialize();
        var url  = $(this).attr('action');
        var post = $(this).attr('method');
        $.ajax({
            type: post,
            url: url,
            data: data,
            dataTy: 'json',
            success:function(data)
            {
                $('.error').remove();
          $('#table').append("<tr class='post" + data.id + "'>"+
            "<td>" + data.id + "</td>"+
            "<td>" + data.division_id.name + "</td>"+
            "<td>" + data.code + "</td>"+
            "<td>" + data.name  + "</td>"+
            "<td>" + data.created_at + "</td>"+
            "<td><button class='show-modal btn btn-info btn-sm' data-id='" + data.id + "' data-division_id.name='" +
             data.division_id.name + "' data-code='" +
             data.code + "' data-name='" +
             data.name + "'><span class='fa fa-eye'></span></button> <button class='edit-modal btn btn-warning btn-sm' data-id='" + data.id +"' data-division_id.name='" +
             data.division_id.name + "' data-code='" +
             data.code + "' data-name='" +
             data.name + "'><span class='glyphicon glyphicon-pencil'></span></button> <button class='delete-modal btn btn-danger btn-sm' data-id='" + data.id + "' data-division_id.name='" +
             data.division_id.name + "' data-code='" +
             data.code + "' data-name='" +
             data.name + "' ><span class='glyphicon glyphicon-trash'></span></button></td>"+
            "</tr>");
            }
        });
    })
</script>



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-ajax-query-showing-undefined-before-refreshing/
via Lzo Media

Laravel why store array position instead his name - development

Laravel why store array position instead his name

why store array position instead his name.

BLADE

My blade file where i have my list of category

<div class="col-md-2">
                <div class="form-group">
                    <label for="role">Category</label>
                    <div class="fg-line">
                        <div class="select">
                        {!! Form::select('category', $categorylist,null,array('class' => 'form-control')) !!}
                        </div>
                    </div>
                </div>

controller

my controller where take data from query to send to blade file

$categorylist = Category::where('category','=','cat')
                    ->groupby('catlist')
                    ->pluck('catlist');

                    //dd($categorylist);


return view('addcategory')
    ->with(
        [
            'categorylist' => $categorylist
        ]
);



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-why-store-array-position-instead-his-name/
via Lzo Media

Wednesday, April 25, 2018

Is it possible to set up a custom laravel websocket server? - development

Is it possible to set up a custom laravel websocket server?

Is it possible to create a custom websocket server in laravel if you dont want to use pusher or any other external service ? …. can you redirect me to some good documentations



from Laravel Questions and Answers https://laravelquestions.com/laravel/is-it-possible-to-set-up-a-custom-laravel-websocket-server/
via Lzo Media

How to handle authorization for a non-user based Laravel API? - development

How to handle authorization for a non-user based Laravel API?

I have a Laravel web application for a restaurant with its own user base.
I have another web application for a bookstore with its own different user base.

I would like to create a third application (mostly API, probably using Lumen) that can create accounting records from both the restaurant and the bookstore on every transaction that is made (i.e. when I sell any food, make a POST request to this API to insert a record, and do the same if I sell a book).

How can I guarantee that only authorized users from my web apps (any user) can make requests to my API, without asking them for any additional password?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-handle-authorization-for-a-non-user-based-laravel-api/
via Lzo Media

Relations help Laravel - development

Relations help Laravel

I have a problem with relations and can’t solve that.

I have 3 models:

1st CarRepair

This has function:

public function parts_list()
{
return $this->hasMany('AppRepairPart', 'repair_id')->orderBy('position', 'ASC');
}

2nd RepairPart (has columns user_id and car_id)

This has function:

public function worker() {
return $this->belongsTo('AppWorker', 'worker_id');
}

3rd Car

This has function:

public function current_repair()
{
return $this->hasOne('AppCarRepair')->where('status', 0);
}

I want to create function in CarRepair model that would return me a list of CurrentRepair workers.

Sorry for my bad english. Hope you guys understood 🙂



from Laravel Questions and Answers https://laravelquestions.com/laravel/relations-help-laravel/
via Lzo Media

Can I make web services in laravel framework if the project is in cakephp3 - development

Can I make web services in laravel framework if the project is in cakephp3

I am working on a project which is created in cakephp3 and I need to make API for my android app.
I have a little knowledge of Laravel and I can make API in Laravel.
My question is can I make APIs in Laravel if my project is created in cakephp3.
any help will be appreciable. Thanks, in advance.



from Laravel Questions and Answers https://laravelquestions.com/php/can-i-make-web-services-in-laravel-framework-if-the-project-is-in-cakephp3/
via Lzo Media

many to many. Get error during additional column saving to database - development

many to many. Get error during additional column saving to database

Many to many relationships in the model

  public function drycleanings()
    {
      return $this->belongsToMany('Appdrycleaning')
      ->withPivot('$cart_id','drycleaning_id','q_drycleaning_id');
    }

and

  public function carts()
  {
    return $this->belongsToMany('Appcart')
    ->withPivot('$cart_id','drycleaning_id','q_drycleaning_id');
  }

In the controller I am using

$cart->drycleanings()->attach($request->drycleaning_id,[$request->q_drycleaning_id]);

if gives me an error

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘0’ in ‘field list’

Result of dd($request->all());

"drycleaning_id" => array:2 [▼
    0 => "3"
    1 => "4"
  ]
  "q_drycleaning_id" => array:58 [▼
    0 => "2"
    1 => "2"
    2 => null
    3 => null
    4 => null
    5 => null
    6 => null
    7 => null
    8 => null
    9 => null
    10 => null
  ]

Migration for cart_drycleaning table

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateCartDrycleaningTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cart_drycleaning', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('cart_id');
            $table->integer('drycleaning_id');
            $table->integer('q_drycleaning_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cart_drycleaning');
    }
}

If I use only $cart->drycleanings()->attach($request->drycleaning_id);
then cart_id and drycleaning_id gets stored into association/pivot table (table name: cart_drycleaning)

I am trying to save q_drycleaning_id (represent quantity of item) getting as input from user.

Is there any way I can only pass non-null values? or any other solution to save both into association table?



from Laravel Questions and Answers https://laravelquestions.com/laravel/many-to-many-get-error-during-additional-column-saving-to-database/
via Lzo Media

npm doesnt build latest file - development

npm doesnt build latest file

Maybe I am doing it wrong. I have modified a .vue template in node_modules folder. Now when I run npm run watch or npm run dev it doesn’t get reflected in UI.

I am using Laravel 5.6 with Laravel Mix
Any idea whats wrong ?

thanks

Chintan



from Laravel Questions and Answers https://laravelquestions.com/laravel/npm-doesnt-build-latest-file/
via Lzo Media

Alexa Smart Home set URL to my website for discovery - development

Alexa Smart Home set URL to my website for discovery

​I am following the: Steps to Build a Smart Home Skill
https://developer.amazon.com/docs/smarthome/steps-to-build-a-smart-home-skill.html

I have followed the steps but I can’t figure out where to set the url to my website.
What I need is how to point the discovery to my website. https://mywebsite/api/alexa/discovery.
In the lambda code I don’t see where to set this url.

I have set the urls for oauth2 in the skill :
https://mywebsite/oauth/authorize
https://mywebsite/oauth/token

When I created the Alexa ASK skill to test my website it provides a endpoint default region.
My ask skill works great with the oauth to my website.

Also I would like to point the handlePowerControl to the https://mywebsite/api/alexa/control

NOTE: My website is done with laravel and the oauth is done with passport.

What am I missing?



from Laravel Questions and Answers https://laravelquestions.com/laravel/alexa-smart-home-set-url-to-my-website-for-discovery/
via Lzo Media

invalid_credentials on JWT auth laravel - development

invalid_credentials on JWT auth laravel

I’m using jwt-auth for auth API with laravel and write following code.

My register API working good bug my login API return invalid_credentials error.
why?

laravel version: 5.4

public function login(Request $request) {

    $credentials = $request->only('username', 'password');

    try {
        $token = JWTAuth::attempt($credentials);
        if (!$token) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error' => 'could_not_create_token'], 400);
    }

    return response()->json(compact('token'), 200);
}

public function register(Request $request) {

    $credentials = $request->only('email', 'username', 'password', 'name');

    $validator = Validator::make($credentials, [
        'name' => 'required|max:80',
        'username' => 'required|max:80|unique:users',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6',
    ]);

    if ($validator->fails()) {
        $errors = $validator->errors();
        return response()->json(['error' => array(
            'name'     => $errors->first('name'),
            'email'    => $errors->first('email'),
            'username'    => $errors->first('username'),
            'password' => bcrypt('password'),
        )], 400);
    }

    $user = User::create([
        'name'      => $request->name,
        'email'     => $request->email,
        'username'  => $request->username,
        'password'  => $request->password,
    ]);

    $token = JWTAuth::fromUser($user);
    return response()->json(compact('token'));
}



from Laravel Questions and Answers https://laravelquestions.com/php/invalid_credentials-on-jwt-auth-laravel/
via Lzo Media

I wrote a tutorial on how to integrate Facebook PHP SDK with Laravel 5.6 and use it for publishing to user Profiles and Pages - development

I wrote a tutorial on how to integrate Facebook PHP SDK with Laravel 5.6 and use it for publishing to user Profiles and Pages

I wrote a tutorial on how to integrate Facebook PHP SDK with Laravel 5.6 and use it for publishing to user Profiles and Pages submitted by /u/waleed_ahmad
[link] [comments]


from Laravel Questions and Answers https://laravelquestions.com/rlaravel/i-wrote-a-tutorial-on-how-to-integrate-facebook-php-sdk-with-laravel-5-6-and-use-it-for-publishing-to-user-profiles-and-pages/
via Lzo Media

How to get value from an array in vue.js - development

How to get value from an array in vue.js

I have an array:

{ "id": 1, 
  "title": "Incidunt facere placeat nulla occaecati voluptatem voluptatem minus.", 
  "categories": [ 
     { "id": 1, 
      "name": "News", 
      "created_at": "2018-04-23 18:05:47", 
      "updated_at": "2018-04-23 18:05:47", 
      "pivot": { 
      "post_id": 1, 
      "category_id": 1 } }, { 
      "id": 2, 
      "name": "Sport", 
      "created_at": "2018-04-23 18:05:47", 
      "updated_at": "2018-04-23 18:05:47", 
      "pivot": { 
        "post_id": 1, 
        "category_id": 2 
        } 
       } 
     ]}

I can simply use to have the post title, but when I do it returns null because its not an array.

Is there anyway to have category name?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-get-value-from-an-array-in-vue-js/
via Lzo Media

Tuesday, April 17, 2018

Eloquent create says column has no default value using Laravel 5 - development

Eloquent create says column has no default value using Laravel 5

I have an small API that i want to save into client mysql database.
For this purpose i’m using guzzle.

my controller:

 public function index()
    {
        $http = new GuzzleHttpClient;
        $res = $http->request('GET', 'http://localhost:8080/api/address');
        $addresses = json_decode($res->getBody(),true);   
        // dd($addresses);
        Address::create($addresses);
    }

my model:

class Address extends Model
{
    protected $primaryKey = 'Adresse';
    protected $fillable = ['Adresse', 'Mandant', 'Kategorie', 'Matchcode', 'Name1'];

    public $timestamps = false;

}

my migration:

public function up()
{
   Schema::create('addresses', function (Blueprint $table) {
        $table->integer('Adresse')->primary();
        $table->smallInteger('Mandant');
        $table->smallInteger('Kategorie')->nullable();
        $table->string('Matchcode', 50);
        $table->string('Anrede', 50)->nullable();
        $table->string('Name1', 50)->nullable();
   });
}

my api content:

[
{"Adresse":"1111","Mandant":"0","Kategorie":"0","Matchcode":"fgh8881","Anrede":"Firma","Name1":"Sample name"},{"Adresse":"2399","Mandant":"0","Kategorie":"0","Matchcode":"fgh8882","Anrede":"Firma","Name1":"Sample name 1"}
]

the problem is i get an error

SQLSTATE[HY000]: General error: 1364 Field ‘Adresse’ doesn’t have a
default value (SQL: insert into addresses () values ())

when i limit the api content to one array i can save it without a problem. But if i have more arrays in my api i get this error.
$fillable property on the model is set.



from Laravel Questions and Answers https://laravelquestions.com/php/eloquent-create-says-column-has-no-default-value-using-laravel-5/
via Lzo Media

Notification with Laravel Elasticsearch - development

Notification with Laravel Elasticsearch

We are out of ideas on the proper approach to this scenario.

We have a system, where users can set up some search criteria’s and save it, if there are any matches found in the system we will show results.

But we need to set up a cronjob, where if any new matches found (these can be either updated records or new records) then we have to give a count of newly matched records notification icon, on click, on that need to show a list of new matched records to the user who has created the search criteria.

At this moment we are not storing the search results in the database, is there any approach that we can achieve this without saving the matched records to a table.

We are thing that, if we save the results into the database it becomes huge in the very near future.

Sorry for grammatical mistakes, hope I conveyed problem clearly.

May be my problem is very close the stackoverflow inbox alert concept.



from Laravel Questions and Answers https://laravelquestions.com/php/notification-with-laravel-elasticsearch/
via Lzo Media

Laravel Homestead remove host only adapter - development

Laravel Homestead remove host only adapter

in my laravel Homestead project i need to change the Host Only virtual box adapter to Bridged Network adapter.

I always end up having 3 Adapters: 1 NAT, 1 Host Only and 1 Bridged Networking.

What i want to achieve is that i have only one Bridged Networking adapter.

I’ve been searching since two days to find a solution but still havent been able to solve this.
What I’ve been doing is, that ive been debugging through the homestead.rb script they are distributing and trying to find the spots i need to edit. What also came in my mind that those two adapters might be the default virtualboxes.
But i should be able to at least deactivate them somehow in the Homestead.yml

Any ideas on how i can fix this?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-homestead-remove-host-only-adapter/
via Lzo Media

Laravel – Retrieve result from relation - development

Laravel – Retrieve result from relation

I need some help from anyone to resolve this problem.
I have create a small project in Laravel.
I have two tables: cables and associations.

cables
id | cable | price

1 | OMDS001 | 144.50
2 | OMDS001-MC | 152.70
3 | OMDS001-NC | 149.00
4 | AR-T4CR | 167.90


associations
cable_id | cable_associated_id

1 | 2
1 | 3


The relationship is: one cable hasMany associaton
I have to set the final sale price.

The constraint is that if the cables are associated with each other (as 1, 2 and 3), the final selling price of each must be the highest.

In this specific case the final sales prices must be:

1 | OMDS001 | 152.70
2 | OMDS001-MC | 152.70
3 | OMDS001-NC | 152.70
4 | AR-T4CR | 167.90

The value must be visual only and must not be entered in the database.
Thanks for eventually help.



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-retrieve-result-from-relation/
via Lzo Media

HTTP 401 Unable to create record Twillio PHP sdk 5.16 - development

HTTP 401 Unable to create record Twillio PHP sdk 5.16

I am using Twilio account for the sending SMS to users. I have installed the SDK by executing following command.

composer require twilio/sdk

and i am using the following code snippet to send message

public function sendSms($data) {
    // Your Account SID and Auth Token from twilio.com/console
    $account_sid = 'sid';
    $auth_token = 'token';
    $twilio_number = "number";
    $client = new Client($account_sid, $auth_token);
    return $client->messages->create(
               $data['phone'], array(
               'from' => $twilio_number,
               'body' => $data['message'],
             )
    );
}

according to twillio documentation message should be sent by this code on providing my valid credentials but i am getting the error

[HTTP 401] Unable to create record:
Authenticate85/var/www/art/api/vendor/twilio/sdk/Twilio/Version.php

I have done research on this issue but I got no guidance any clues?

Note: I have balance in my Twilio account



from Laravel Questions and Answers https://laravelquestions.com/php/http-401-unable-to-create-record-twillio-php-sdk-5-16/
via Lzo Media

how to join in laravel on a select result with eloquent? - development

how to join in laravel on a select result with eloquent?

I want to join on a result of other select like this :

SELECT *
  FROM TABLE1
  JOIN (
  SELECT cat_id FROM TABLE2 where brand_id = 2 GROUP BY TABLE2.cat_id) AS b ON TABLE1.id = b.cat_id

is there any way to do this with eloquent?



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-join-in-laravel-on-a-select-result-with-eloquent/
via Lzo Media

Cache remember specific parameter in get request end up the same result – Laravel 5 - development

Cache remember specific parameter in get request end up the same result – Laravel 5

trying too search any matching name get request with different parameter for example: search?q=anhar showing the result with the name anhar then when I change anhar with aslam its not querying again and endup with the same result

here’s my controller

public function search(Request $request)
    {
        $q = $request->get('q');
        $q = Cache::remember('q', 30*60, function() use ($q) {
            $user = User::select('users.id', 'users.first_name', 'users.last_name', 'profiles.location', 'profiles.occupation')
                        ->leftJoin('profiles', 'users.id', '=', 'profiles.member_id')
                        ->where('first_name', 'LIKE', '%'.$q.'%')
                        ->orWhere('last_name', 'LIKE', '%'.$q.'%')
                        ->paginate(10);
            return $user;
        });
        return view('search.result', compact('q'));
    }

and this route

Route::get('/search', 'PublicController@search')->name('search.result');



from Laravel Questions and Answers https://laravelquestions.com/laravel/cache-remember-specific-parameter-in-get-request-end-up-the-same-result-laravel-5/
via Lzo Media

what is the laravel command to deploy the enter database without seed? - development

what is the laravel command to deploy the enter database without seed?

Hi i would like to command to deploy the entire database without seed. and I have some other questions as well related to laravel. I want to convert following sql query to laravel eloquent format.

select * from user where id = '123' and password = 'abcd';
select name, address from user where lower('name') like lower('%Jerry%');



from Laravel Questions and Answers https://laravelquestions.com/php/what-is-the-laravel-command-to-deploy-the-enter-database-without-seed/
via Lzo Media

Get dealership under a company - development

Get dealership under a company

I have branch index page it contains 2 drop-down menu called company and dealership when i click on company it contains a company i created when click on a company the corresponding dealership should list in the dealership dropdown. i used eloqent straightly into index page i did that because the i can’t access the company and dealership in the index page

    Index

 @include('theme.header')

    <?php  use IlluminateSupportFacadesDB;?>


    <div class="page-content-wrapper ">

        <div class="container-fluid">

            <div class="row">
                <div class="col-sm-12">
                    <div class="page-title-box">
                        <div class="btn-group float-right">

                        </div>
                        <h4 class="page-title">Branch Management</h4>
                    </div>
                </div>
            </div>
            <!-- end page title end breadcrumb -->

            <div class="row">
                <div class="col-12">
                    <div class="card m-b-30">
                        <div class="card-body">

                            <h4 class="mt-0 header-title">Branch</h4>
                            <br>
                            <br>
                            <form id="form" method="post" action="">
                                
                                <div class="form-group row">
                                    <label class="col-sm-2 col-form-label">Company</label>
                                    <div class="col-sm-10">

                                        <select class="form-control" id="company" name="company">

                                            <option>Select Company</option>
                                            @foreach(AppCompany::all()->where('status','0') as $company)
                                                <option value=""></option>
                                            @endforeach

                                        </select>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label class="col-sm-2 col-form-label">Dealership</label>
                                    <div class="col-sm-10">
                                        <select class="form-control" id="dealer" name=" dealer">
                                            <option>Select Dealership</option>
                                            @foreach(AppDealership::join('companies','comp_id','=','dealerships.comp_id')->where('status','0') as $dealership)

                                                <option value=""></option>
                                            @endforeach

                                        </select>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="example-text-input" class="col-sm-2 col-form-label">Email</label>
                                    <div class="col-sm-10">
                                        <input class="form-control" type="email" id="email" name="email" required>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label for="example-text-input" class="col-sm-2 col-form-label">Branch Name</label>
                                    <div class="col-sm-10">
                                        <input class="form-control" type="text" id="branch" name="branch" required>
                                    </div>
                                </div>


                                <div class="row">
                                    <div class="col-sm-12">
                                        <div class="page-title-box">
                                            <div class="btn-group float-right">
                                                <button class="btn btn-primary" id="btn_save" data-toggle="modal"
                                                        data-target="#create" type="submit">Save
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </form>


                        </div>
                    </div>


     @include('theme.footer')



from Laravel Questions and Answers https://laravelquestions.com/laravel/get-dealership-under-a-company/
via Lzo Media

Laravel Base table or view not found in a new fresh database - development

Laravel Base table or view not found in a new fresh database

I came across the following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'street-box.chanels' doesn't exist

So, after hours trying to find the erroor I gave up and did the following:

  • I made a backup of everything.
  • I “GIT” and created a new branch.
  • I deleted the database and created a new one fresh with a new name.
  • I declare the new database in the .ENV file
  • I deleted all migrations and let just the passwords and user migrations unchanged (fresh).
  • I deleted the log file and emptied the storageframeworkviews directory
  • I restarted the server.

Basically I have a new app. My goal ist migrate one by one each table to figure out where the problem is.

I run the first migration (just user table and passwords)

php artisan migrate

and get the exact same error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'street-box.chanels' doesn't exist

The question is:

Where Laravel store the information about tables if I have not migrations and a fresh database with a new name?

EDIT: My migrations are fresh, out of the box. The new database has the same name

Usertable

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('role_id')->index()->default(3);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Passwort

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatePasswordResetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('password_resets');
    }
}



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-base-table-or-view-not-found-in-a-new-fresh-database/
via Lzo Media

Monday, April 16, 2018

Adding a XOR constraint via Laravel migration - development

Adding a XOR constraint via Laravel migration

I am trying to build a table of this structure using Laravel’s migrations feature:

------------------------------------
| Data  | Rules | Allow | Restrict |
------------------------------------
| item1 | rule1 | 1,3   |   null   |
| item2 | rule2 | null  |  2,5,6   |
------------------------------------

As in, for each entry either Allow or Restrict must possess a not null value, but not both. I’ve found this comment which sounds like the condition I need, but I need to express it in a format understandable to Laravel.



from Laravel Questions and Answers https://laravelquestions.com/php/adding-a-xor-constraint-via-laravel-migration/
via Lzo Media

flash message if user is not login laravel - development

flash message if user is not login laravel

When user tried to go user dashboard without login, it return to login page. it works perfectly. but I need to show message on login page using middleware that ‘please login to see this page.’

I tried {!! $errors->first(‘loginpermission’, ‘:message’) !!}

But it not working

Please help me how to use this.



from Laravel Questions and Answers https://laravelquestions.com/php/flash-message-if-user-is-not-login-laravel/
via Lzo Media

New Laravel Routes not working - development

New Laravel Routes not working

I have a problem, new routes in laravel are not working, url shows the correct route but almost as if it does not get to my routes web file just returns page not found every time.

I have tried:
using named route,
moving function to different controller,
clearing route cache,
clearing app cache,
dump-auto load,
made sure that AllowOverride is set to All,

Web.php:

    <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

/*
|--------------------------------------------------------------------------
| Courses
|--------------------------------------------------------------------------
*/
Route::get('/courses', 'CourseController@index');
Route::get('/courses/create', 'CourseController@create');
Route::get('/courses/{course}', 'CourseController@show');
Route::get('/courses/{course}/edit', 'CourseController@edit');
Route::post('/courses', 'CourseController@store');
Route::patch('/courses/{course}', 'CourseController@update');
Route::delete('/courses/{course}', 'CourseController@destroy')->name('course-delete');

Route::get('/courses/statistics', 'CourseController@statistics');

/*
|--------------------------------------------------------------------------
| First Aid
|--------------------------------------------------------------------------
*/
Route::get('/section/{section}', 'SectionController@show');


/*
|--------------------------------------------------------------------------
| First Aid
|--------------------------------------------------------------------------
*/
Route::get('/progress', 'UserProgressController@index');
Route::get('/progress/create', 'UserProgressController@create');
Route::get('/progress/{section}', 'UserProgressController@show');
Route::get('/progress/formativeresults', 'UserProgressController@formativeresults');
//Route::get('/progress/coursestatistics', 'UserProgressController@coursestatistics');
//Route::get('/progress/{progress}/edit', 'UserProgressController@edit');
Route::post('/progress', 'UserProgressController@store');
//Route::patch('/progress/{progress}', 'UserProgressController@update');
//Route::delete('/progress/{progress}', 'UserProgressController@destroy')->name('progress-delete');

Controller:

public function statistics()
    {
        dd('Test');
       return view('coursestatistics');
    }

View file name:
coursestatistics.blade.php file structure views/coursestatistics

Link to page:

<a class="navbar-brand" href="/courses/statistics">
   
</a>

Can anyone tell me what might be causing route not to work?



from Laravel Questions and Answers https://laravelquestions.com/php/new-laravel-routes-not-working/
via Lzo Media

Laravel router namespace method - development

Laravel router namespace method

In Laravel documentation routing there is a namespace method.

Route::namespace

I tried to explore what does it really do but couldn’t find it’s definition in Laravel source codes. Where is it?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-router-namespace-method/
via Lzo Media

How to use date time picker in sweet alert? - development

How to use date time picker in sweet alert?

This is my code i am working on

   swal({
                title: "Confirm details?",
                text:'<input id="datetimepicker" class="form-control" autofocus>',
                type: "warning",
                customClass: 'swal-custom-width',
                html:true,
                showCancelButton: true,
                confirmButtonClass: "btn-success",
                confirmButtonText: "Confirm",
                cancelButtonText: "Cancel",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            },

I want to set date time picker in the input inside sweet alert.

$('#datetimepicker').datetimepicker({
    format: 'DD/MM/YYYY hh:mm A',
    defaultDate: new Date()
});

When i clicked on the sweet alert, the input field unable to click or do any action on it. The date also didnt show up. Anyone can tell me what’s wrong? Thanks.

Console error when click on input select date

Uncaught RangeError: Maximum call stack size exceeded.
at HTMLDivElement.trigger (jquery-2.2.3.min.js:3)
at Object.trigger (jquery-2.2.3.min.js:4)
at HTMLDivElement.<anonymous> (jquery-2.2.3.min.js:4)
at Function.each (jquery-2.2.3.min.js:2)
at n.fn.init.each (jquery-2.2.3.min.js:2)
at n.fn.init.trigger (jquery-2.2.3.min.js:4)
at c.<anonymous> (bootstrap.min.js:6)
at HTMLDocument.f (jquery-2.2.3.min.js:2)
at HTMLDocument.dispatch (jquery-2.2.3.min.js:3)
at HTMLDocument.r.handle (jquery-2.2.3.min.js:3)



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-use-date-time-picker-in-sweet-alert/
via Lzo Media

Using PHP and MySQL data to generate PDF letters like in MS Word mailmerge functionality - development

Using PHP and MySQL data to generate PDF letters like in MS Word mailmerge functionality

I would really like to know if there is a way like MS Word mailmerge functionality that can be done using PHP and Mysql data. Like i have address data in MySQL (suppose 10 numbers) and through PHP i want to insert that address data in a pre-defined letter head area. And it will automatically generate 10 different letters with same content but different address in PDF. Can it be done? Any start up point will be helpful. As I am working on Laravel so any snippet of that sort will also be useful.

Thanks in advance.



from Laravel Questions and Answers https://laravelquestions.com/php/using-php-and-mysql-data-to-generate-pdf-letters-like-in-ms-word-mailmerge-functionality/
via Lzo Media

CSRF token error? on laravel Symfony\Component\HttpKernel\Exception\HttpException - development

CSRF token error? on laravel SymfonyComponentHttpKernelExceptionHttpException

first was ok. second got error
enter image description here
I use the ajax function on javascript page in laravel

If I initiate the function once it work well
But when I start the function 2 or 3 times in short time I got the error

"exception": "SymfonyComponentHttpKernelExceptionHttpException",
"file": "D:AppServwwwcomevendorlaravelframeworksrcIlluminateFoundationExceptionsHandler.php",

I search the error message . The result is the csfr issue.

But how can I fix the error?
I have already have the

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

The question is not on the first time . It’s on the second or third times.

Code

$('.findNews_geography').autocomplete({   
        source: function(request, response) {
            var findtable=$('.findtable_num').val();
            var terms=request.term; 
            console.log("findtable="+findtable+";term="+terms);
            $.ajax({
                headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },


                url: "findNews_geography",
                dataType: "json",
                type: "post",
                data: {
                    findtable : findtable,
                    term : terms,
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    console.log("findNews_geography ajax error="+xhr.responseText);
                    console.log("findNews_geography xhr.status="+xhr.status+";thrownError="+thrownError);
                },
                success: function(data) {
                    console.log("see request="+data);
                    response( $.map( data, function( item ) {
                        return {
                            label: item.place,
                        }

                    }));
                } //success end
            }); //ajax end
        }, //source end
        minLength: 0, 
}); //autocomplete end




 $(".findNews_geography").focus(function () {
         //if (this.value == "") {
       console.log("findNews_geography get focus");
        if($('.findtable_num').val()){
            $(this).autocomplete("search"); 
        }// }; 
  });



from Laravel Questions and Answers https://laravelquestions.com/laravel/csrf-token-error-on-laravel-symfonycomponenthttpkernelexceptionhttpexception/
via Lzo Media

how to create global variable in laravel 5.6 - development

how to create global variable in laravel 5.6

I want to create a global variable for my entire project in Laravel’s framework so that I can create it in a class and make it everywhere anyone can guide it?



from Laravel Questions and Answers https://laravelquestions.com/php/how-to-create-global-variable-in-laravel-5-6/
via Lzo Media

Convert payload to json in laravel - development

Convert payload to json in laravel

I get a form data in Laravel

$request->getContent();

Result is:

"""
------WebKitFormBoundaryNBoGTqDMmoBbVxmNrn
Content-Disposition: form-data; name="avatar"rnrn data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...AAABBESAIAgQgIAEERIAACCCAkAQBAhA   QAIIiQAAEGEBAAg4H//+z90ysSjp0MzewAAAABJRU5ErkJggg==rn------WebKitFormBoundaryNBoGTqDMmoBbVxmN--rn"""

How can I parse it to json in laravel?



from Laravel Questions and Answers https://laravelquestions.com/laravel/convert-payload-to-json-in-laravel/
via Lzo Media

save collection in global variable in laravel 5.6 - development

save collection in global variable in laravel 5.6

so basically i have an index page where i have to go to controller to fetch data from database

route:-

route::get('/index/{$x}', 'indexController@index');

index controller:-

$data = Data::where('name', $x)->get();
return View::make('index', compact('data');

then inside index page i have link that goes to second page
with same data, i d not want to query the same data as it may affect performance

route:-

route::get('/second', indexController@second);});

Second Controller:-

$data = $data->sortBy('id');
return View::make('second', compact('data');

i thought of saving data in global variable in controller

so i added private variable inside controller and try to access it through $this->data

but it did not work cause based on my search the controller will be closed after it returns view

so if i try access $this->data inside second function it will be empty

is it possible to save queried data (collection) in global variable

as i do not want to query same data for every page

your help will be appreciated



from Laravel Questions and Answers https://laravelquestions.com/laravel/save-collection-in-global-variable-in-laravel-5-6/
via Lzo Media

Sunday, April 15, 2018

laravel form delete request not working - development

laravel form delete request not working

Just making a delete request from a form but not working. can you help please ?

<form method="POST" action="/products/"> 
    @csrf
    @method('DELETE')
    <button type="submit">delete</button>

here is my route:

Route::delete('/products/{del}',function($del){
    return $del.' deleted';
});

this give no errors, i just have a blank page



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-form-delete-request-not-working/
via Lzo Media

Lumen Queue Job cannot connect to database - development

Lumen Queue Job cannot connect to database

I’m new to Lumen and writing some codes that will enqueue jobs using Lumen queue. (Lumen version 5.6)
Models will be used in the job.
My model works like a charm in the controller.
However, my models in the job cannot access to database when I try to query something.

Can somebody can help me because I think Lumen Job can access to any Model just like controllers.

Controller

use IlluminateHttpRequest; 
use AppJobssomeJob;
use AppHttpControllersController;

class myController extends BaseController {
    public function enqueueJob(Request $request){
        $json = [
            'some_payload' => 'test payload'
        ];
        Queue::push(new someJob($json));
    }
}

Model

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class MyModel extends Model{
    protected $table = 'table_name';
    protected $connection = 'connection_name';

}

app/Jobs/Job.php

namespace AppJobs;

use IlluminateBusQueueable;
use IlluminateQueueSerializesModels;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;

abstract class Job implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;
}

app/Jobs/someJob.php

namespace AppJobs;

use AppModelsMyModel;

class someJob extends Job
{

    protected $json;
    public function __construct($json){
        $this->json = $json;
    }

    public function handle(){
        $json = json_decode($this->json);
        MyModel::find($json->id);  // Error here!
    }
}

It throws the following errors

[2018-04-15 08:51:39] production.ERROR: PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /path/to/project/vendor/illuminate/database/Connectors/Connector.php:68
#0 /path/to/project/vendor/illuminate/database/Connectors/Connector.php(68): PDO->__construct('mysql:host=mysq...', NULL, NULL, Array)
#1 /path/to/project/vendor/illuminate/database/Connectors/Connector.php(44): IlluminateDatabaseConnectorsConnector->createPdoConnection('mysql:host=mysq...', NULL, NULL, Array)
#2 /path/to/project/vendor/illuminate/database/Connectors/MySqlConnector.php(24): IlluminateDatabaseConnectorsConnector->createConnection('mysql:host=mysq...', Array, Array)
#3 /path/to/project/vendor/illuminate/database/Connectors/ConnectionFactory.php(183): IlluminateDatabaseConnectorsMySqlConnector->connect(Array)
#5 /path/to/project/vendor/illuminate/database/Connection.php(915): call_user_func(Object(Closure))
#6 /path/to/project/vendor/illuminate/database/Connection.php(452): IlluminateDatabaseConnection->getPdo()
#7 /path/to/project/vendor/illuminate/database/Connection.php(657): IlluminateDatabaseConnection->IlluminateDatabase{closure}('insert into `fa...', Array)
#8 /path/to/project/vendor/illuminate/database/Connection.php(624): IlluminateDatabaseConnection->runQueryCallback('insert into `fa...', Array, Object(Closure))
#9 /path/to/project/vendor/illuminate/database/Connection.php(459): IlluminateDatabaseConnection->run('insert into `fa...', Array, Object(Closure))
#10 /path/to/project/vendor/illuminate/database/Connection.php(411): IlluminateDatabaseConnection->statement('insert into `fa...', Array)
#11 /path/to/project/vendor/illuminate/database/Query/Processors/Processor.php(32): IlluminateDatabaseConnection->insert('insert into `fa...', Array)
#12 /path/to/project/vendor/illuminate/database/Query/Builder.php(2204): IlluminateDatabaseQueryProcessorsProcessor->processInsertGetId(Object(IlluminateDatabaseQueryBuilder), 'insert into `fa...', Array, NULL)
#13 /path/to/project/vendor/illuminate/queue/Failed/DatabaseFailedJobProvider.php(62): IlluminateDatabaseQueryBuilder->insertGetId(Array)
#14 /path/to/project/vendor/illuminate/queue/Console/WorkCommand.php(188): IlluminateQueueFailedDatabaseFailedJobProvider->log('redis', 'default', '{"displayName":...', 'ErrorException:...')
#15 /path/to/project/vendor/illuminate/queue/Console/WorkCommand.php(137): IlluminateQueueConsoleWorkCommand->logFailedJob(Object(IlluminateQueueEventsJobFailed))
#16 /path/to/project/vendor/illuminate/events/Dispatcher.php(360): IlluminateQueueConsoleWorkCommand->IlluminateQueueConsole{closure}(Object(IlluminateQueueEventsJobFailed))
#17 /path/to/project/vendor/illuminate/events/Dispatcher.php(209): IlluminateEventsDispatcher->IlluminateEvents{closure}('IlluminateQueu...', Array)
#18 /path/to/project/vendor/illuminate/queue/FailingJob.php(36): IlluminateEventsDispatcher->dispatch('IlluminateQueu...')
#19 /path/to/project/vendor/illuminate/queue/Worker.php(435): IlluminateQueueFailingJob::handle('redis', Object(IlluminateQueueJobsRedisJob), Object(ErrorException))
#20 /path/to/project/vendor/illuminate/queue/Worker.php(421): IlluminateQueueWorker->failJob('redis', Object(IlluminateQueueJobsRedisJob), Object(ErrorException))
#21 /path/to/project/vendor/illuminate/queue/Worker.php(353): IlluminateQueueWorker->markJobAsFailedIfWillExceedMaxAttempts('redis', Object(IlluminateQueueJobsRedisJob), 1, Object(ErrorException))
#22 /path/to/project/vendor/illuminate/queue/Worker.php(326): IlluminateQueueWorker->handleJobException('redis', Object(IlluminateQueueJobsRedisJob), Object(IlluminateQueueWorkerOptions), Object(ErrorException))
#23 /path/to/project/vendor/illuminate/queue/Worker.php(272): IlluminateQueueWorker->process('redis', Object(IlluminateQueueJobsRedisJob), Object(IlluminateQueueWorkerOptions))
#24 /path/to/project/vendor/illuminate/queue/Worker.php(229): IlluminateQueueWorker->runJob(Object(IlluminateQueueJobsRedisJob), 'redis', Object(IlluminateQueueWorkerOptions))
#25 /path/to/project/vendor/illuminate/queue/Console/WorkCommand.php(101): IlluminateQueueWorker->runNextJob('redis', 'default', Object(IlluminateQueueWorkerOptions))
#26 /path/to/project/vendor/illuminate/queue/Console/WorkCommand.php(85): IlluminateQueueConsoleWorkCommand->runWorker('redis', 'default')
#28 /path/to/project/vendor/illuminate/container/BoundMethod.php(29): call_user_func_array(Array, Array)

Thanks for your help!



from Laravel Questions and Answers https://laravelquestions.com/php/lumen-queue-job-cannot-connect-to-database/
via Lzo Media

Yajra No available engine for AppUser - development

Yajra No available engine for AppUser

I’ve made for my cms admins role
now i have 2 admin roles super admin and normal admin
i have a page that manage users both super admin and normal admin can see it but with different data

here’s the controller code

  public function index()
    {        
         $this->super_admin_role_check();
        return view('admin.users.index');   
    }



    public function usersList(){
        $super_admin_role = Role::where('name','super_admin')->first();
        $is_super_admin=$this->isSuperAdmin();

        if($is_super_admin){
            $data = User::all();
        }else{
            // Admin can get all users except super admin
            $super_admin = DB::table('role_user')->where('role_id',$super_admin_role->id)->first();
            $data = User::where('id','!=',$super_admin->user_id)->first();
        }

        if(!$data){
            $data=[];
        }
        return DataTables::of($data)->make(true);
    }   




    // This function check if the super_admin roles exist or not
    public function super_admin_role_check(){

        $user = Auth::guard()->user();

        $super_admin_role = Role::where('name','super_admin')->first();

        if(!$super_admin_role){

            Artisan::call('db:seed'); 

            // if there's no role factory create super_admin role and assign it to the super admin user
            $super_admin_role = Role::where('name','super_admin')->first();

            DB::table('role_user')->insert([
            'user_id'=>$user->id,'role_id'=>$super_admin_role->id
            ]);

            $permissions = Permission::all();

            // here i give all permissions to the super admin
            foreach($permissions as $permission){

            DB::table('permission_role')->insert(['permission_id'=>$permission->id,
            'role_id'=>$super_admin_role->id
            ]);
            }
        }
        return $super_admin_role;
    }








    // This Function Check if the user is super admin?
    public function isSuperAdmin(){
        $user = Auth::guard()->user();
        $super_admin_role = Role::where('name','super_admin')->first();
        $is_super_admin = DB::table('role_user')->where('user_id',$user->id)->where('role_id',$super_admin_role->id)->first();
        return $is_super_admin;
    }

The problem is that when i’m login as super admin everythings goes well but when i’m login as normal admin i get error “No available engine for AppUser”
in vendoryajralaravel-datatables-oraclesrcDataTables.php
any help please?



from Laravel Questions and Answers https://laravelquestions.com/laravel/yajra-no-available-engine-for-appuser/
via Lzo Media