jeudi 31 janvier 2019

Laravel Eloquent Distinct

i have this table

int id
string title
string year // maybe i'll change this to int??

and i want to loop my data without using another table to create a relationship using Year.

i want an output like this

2018 
 - title1
 - title2
 - title3

i know select distinct and then i have to create another query by the data i collect on select distinct.my question is this possible in eloquent and how? Thanks.



via Chebli Mohamed

Laravel & PHP - Output is not the same in Laravel but working on PHP

Im working on a barcode or qrcode generator and I have a problem, when I integrate my code and asset folders in PHP everything works perfectly fine I can generate the code ! , but when I integrate this to Laravel and put all the links it went down tho it is the similar UI but the output of the program is not working well it is not generating the code.

My folders are placed in public in laravel and main folder only in php

I am currently confused of this problem - when I delete all assets, codes of JS files in PHP, why is it STILL working tho I deleted all the folders like fonts , css and js however in Laravel when I delete the currently said folders, it brings CHANGES tho in PHP everything works and run even tho the codes are deleted and folders are delete. any solution for this?? im wondering is there a setting for this?

P.S I didnt change any single code of them and still confused why it is not working properly in laravel

Is there any possibility to solve this problem?

my links in laravel

CSS & BOOTSTRAP

link href="" rel="stylesheet">
    <link href="" rel="stylesheet">

JS

<script type="text/javascript" src=""></script>


    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
     <script type="text/javascript">

links in PHP

CSS

<link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

JS

   <script type="text/javascript" src="js/filereader.js"></script>
       <script type="text/javascript" src="js/qrcodelib.js"></script>
    <script type="text/javascript" src="js/webcodecamjs.js"></script>



via Chebli Mohamed

Laravel friendship package

can any one please confirm is this package friendship package by hootlex is good for friendship structure like instagram? Is it bug free?

I made my own custom functions using default laravel queries. Now i want more extra feature so want to use plugin.It would be great help.



via Chebli Mohamed

Is there some way to manage multiple domains content and layout through one single Laravel project?

I'm setting up a Laravel project and I want to manage content and layout of different domains through this project. I need to implement in a way how shopify works. You just need to point our naming servers and then you can manage content and layout of different domains. Is there any way in Laravel?



via Chebli Mohamed

Remove Query Parameter from Laravel Scout Pagination Links()?

I'm using Laravel Scout to search for objects in my database, and need to have the results paginated, but Scout is automatically including a 'query' query term in the url in addition to the page number instead of just the page number.

I'm using the Scout built in pagination like so: $page_results = Page::search($validatedData['search_terms'])->paginate(10, 'page_results');

The problem is that instead of just getting the page number as a query, I'm also getting another 'query' stuck in there as well: http://192.168.10.10/wiki/search?query=a&page_results=2

As my route is like this: Route::post('/search', 'SearchController@search'); Its not expecting that query and is sending it to the fallback.

Is there a way to remove the 'query' query from the Scout links()? What I would like ideally is the following as I've got pagination working on other pages just fine by using the Eloquent pagination which doesn't include that extra query term: http://192.168.10.10/wiki/search?page_results=2

Any help would be much appreciated!



via Chebli Mohamed

How to Run Laravel Route Constrains Before Middleware?

I have route something like this /permissions/{uuid} And I have route constrain and middleware.

Constraint Rule: Add in route service provider for all routes it will apply.

Route::pattern('uuid', '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}');

Middleware Rule:

public function handle($request, Closure $next)
{
    $uuid = $request->route('uuid');

    // Check the uuid in DB and throw an exception

    return $next($request);
}

But the problem here was the middleware was running first. I just want to avoid db call if uuid was not a proper format. Can we run constrain rule first.



via Chebli Mohamed

How can i get 3 table data in index in laravel?

I have 3 tables schools, school_Details,ratings ** School**: - id

  • name

  • phone

  • school

  • email

  • status

School details:

-id

  • school_id

  • image

  • status

ratings:

-id

  • school_id
  • rating_value
  • status

both rating &school details have only one row for one school_id.

Now how can i get all details from all 3 tables in index from schoolController



via Chebli Mohamed

Laravel - Search using Ajax, Automatically search when page is open

How can I automatically search the data when I put a value on my textbox let's say the value is fixed. like this <input type="text" name="search" id="search" class="form-control" value="10310" />

the value there is 10310 and when I open the page I want to automatically search that value. right now my search has an ajax and it is working well. but my problem is I cannot automatically search the value when i open the page by putting a value on my textbox.

Expected Output - I want to automatically search the data that my textbox has.

View

            <input type="text" name="search" id="search" class="form-control" value="10310" />



    <div id="divContent">

    </div>    

here is my Ajax Script

<script type="text/javascript">

    $(document).ready(function(){

    fetch_customer_data();

    function fetch_customer_data(query = '')
    {
    $.ajax({
    url:"",
    method:'GET',
    data:{query:query},
    dataType:'json',
    success:function(data)
    {
    $('#divContent').html(data.table_data);
    $('#total_records').text(data.total_data);
    }
    })
    }

    $(document).on('keyup', '#search', function(){
    var query = $(this).val();
    fetch_customer_data(query);
    });
    });

</script>

my Controller

 function actionActualTime(Request $request)
{
 if($request->ajax())
 {
  $output = '';
  $query = $request->get('query');
  if($query != '')
  {
   $data = DB::table('employeefms')
     ->where('last_name', 'like', '%'.$query.'%')
     ->orWhere('first_name', 'like', '%'.$query.'%')
     ->orWhere('employee_no', 'like', '%'.$query.'%')
     ->get();

  }
  else
  {
   $data = DB::table('employeefms')
     ->orderBy('last_name', 'desc')
     ->get();
  }
  $total_row = $data->count();
  if($total_row > 0)
  {
   foreach($data as $row)
   {

    $output .= '
    <div class="container">
     <img height="50px" width="60px" src="/storage/employee_photos/'.$row->employee_photo.'" /><span class="d-none">'.$row->employee_photo.'</span><br><br>
     <p><b>Employee No: </b></p><input type="text" class="form-control col-md-2" value='.$row->employee_no.'></input><br>
     <p><b>Name: </b></p><input type="text" class="form-control col-md-3" value='.$row->last_name.'></input><br><hr>
     </div>
    ';
   }
  }
  else
  {
   $output = '
   <tr>
    <td align="center" colspan="5">No Data Found</td>
   </tr>
   ';
  }
  $data = array(
   'table_data'  => $output,
   'total_data'  => $total_row
  );

  echo json_encode($data);
 }


}



via Chebli Mohamed

Translation problems sql to eloquen. laravel 5.5

How can I translate this sql query to eloquent?

select governor_candidate from governor order by id=3 desc;

I tried to do it, but I need the id field, you can change the value.



via Chebli Mohamed

Laravel 5 - Limit text column characters

I have a Laravel 5 application and i am trying to limit the length of a database TEXT column to 500.

I have it set as..

$table->text('excerpt');

How can I modify this so it is limited to 500 characters?



via Chebli Mohamed

by npm compilation it changes the image path

I am using the Laravel framework with npm. In the scss file i have image path:

background-image: url("../../img/frontend/payments.png");

by compilation when I open the styles.css and look for that image the path is the following:

background-image: url(/images/payments.png?464788fabc66a26cf02344b0dcbcdde2);

How can I change that path, because all my images are in img/ folder.

There is another thing which is bothering me. I need to copy the payments.png in the resources/sass folder, which is copying tha that picture in public/images. So i have the duplicate of each picture. Is it somehow possible to stay all my images in the public/img folder ?



via Chebli Mohamed

Laravel 5.5 view update issue

How about, I made some changes in a view, but these are not reflected, I applied the following commands

php artisan route:clear
php artisan cache:clear
php artisan view:clear
php artisan config:cache

I have deleted the browser history and I have restarted it, but still I do not apply the changes.



via Chebli Mohamed

I need help to implement eloquent in a file in folder /public/

I need help to implement eloquent in a file in floder /public/ I have /public/js/ a file that calls another in php called getData.php, this file in php returns a series of data from a table, I want to access that data with Eloquent but I can not. This is part of a code "external" to Laravel and returns to declare the parameters of Database and I do not want to do it, I want to use eloquent to not have defined the parameters of the database twice.

I have used: namespace iPuerto; (application is called iPuerto) use Illuminate\Support\Facades\DB; but nothing at all.

I get this error: " Fatal error : Uncaught Error: Class 'Illuminate\Support\Facades\DB' not found in ..."

Can someone help me?

Thank you



via Chebli Mohamed

Error whille running composer install on PHP 7.2 Ubuntu

I kept getting this error at the end of my composer install on PHP 7.2 - Laravel 5.1

> php artisan clear-compiled
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 73 and defined in /home/forge/bheng/app/Exceptions/Handler.php:29
Stack trace:
#0 /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(73): App\Exceptions\Handler->report(Object(Error))
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error))
#2 {main}
  thrown in /home/forge/bheng/app/Exceptions/Handler.php on line 29
[2019-01-31 10:29:34] production.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 73 and defined in /home/forge/bheng/app/Exceptions/Handler.php:29
Stack trace:
#0 /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(73): App\Exceptions\Handler->report(Object(Error))
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error))
#2 {main}
  thrown in /home/forge/bheng/app/Exceptions/Handler.php:29
Stack trace:
#0 {main}  



  [Symfony\Component\Debug\Exception\FatalErrorException]                                                                                                                                                                                                                                                                       
  Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given, called in /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 73 and defined in /home/forge/bheng/app/Exceptions/Handler.php:29  
  Stack trace:                                                                                                                                                                                                                                                                                                                  
  #0 /home/forge/bheng/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(73): App\Exceptions\Handler->report(Object(Error))                                                                                                                                                                     
  #1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error))                                                                                                                                                                                                                      
  #2 {main}                                                                                                                                                                                                                                                                                                                     
    thrown                                                                                                                                                                                                                                                                                                                      


Script php artisan clear-compiled handling the post-update-cmd event returned with error code 255
┌──[root@bheng]──[/home/forge/bheng] 
└──  

How can I prevent that ?



via Chebli Mohamed

I search set Column Class for laravel-datatables

In my laravel 5.7/ blade / jQuery v3.3.1 / Bootstrap v4.1.2 app

I use "yajra/laravel-datatables-oracle": "~8.0" library and when I need to change class of some rows depending on value of some field I do :

return Datatables
    ::of($votesCollection)
    ->setRowClass(function ($vote) {
        return $vote->status == 'N' ? ' row_new_status' : ($vote->status == 'I' ? 'row_inactive_status' : '');
    })

It works ok, but I did not find any similar methods for columns. Are there ? Can it be implemented in some way ?

Thanks!



via Chebli Mohamed

How to iterate ajax success to every row in laravel table?

I can only update the first table of my row and others won't do the dynamic input.

This is my RegisterController@fetchtwo

public function fetchtwo(Request $request)
{
    if ($request->get('query')) {
        $query = $request->get('query');
        $data = DB::table('franchises')
            ->where('case_number', 'like', '%' . $query . '%')
            ->get();
        $output = '<ul class="dropdown-menu" style="display:block;">';
        foreach ($data as $row) {
            $output .= '<li class="dropdown-item" value=' . $row->id . '>' . $row->case_number . '</li>';
        }
        $output .= '</ul>';
        echo $output;
    }
}

Inside of my register-unit.blade.php This is inside my bootstrap modal where I can call and update each row in my table.

@foreach ($unit as $user)
     <div class="form-group col-4">
        <label>Case number</label>
        <input id="case_number" type="text" class="form-control" name="case_number" value="">

        <input type="hidden" id="case_number_hidden" value="" name="case_number_hidden">
        <div class="dropdown show " id="case_number_list"></div>
    </div>
    
@endforeach

Script inside my register-unit.blade.php. This code only execute in every first row of the table i paginate

<script type="text/javascript">
    $(document).ready(function(){
        $('#case_number').keyup(function(){
            var query = $(this).val();
            if (query != ''){
                var _token = $('input[name="_token"]').val();
                $.ajax({
                    url:"",
                    method:"POST",
                    data:{query:query, _token:_token},
                    success:function(data){
                        $('#case_number_list').fadeIn();
                        $('#case_number_list').html(data);
                    }
                })
            }
        });
    });

    $(document).on('click', 'li', function(){
        $('#case_number').val($(this).text());
        let y = $(this).val();
        $('#case_number_hidden').attr('value', y);
        $('#case_number_list').fadeOut();
    });
</script>

How can I iterate this to every row? or make all input tag dynamic where id equals case_number?



via Chebli Mohamed

Laravel Eloquent Nested Relationship group by

I have three models Spot, DealItem and Daypart each has its own relationships

class Spot extends Model
{
   protected $table = 'avt_spot';
   public $timestamps = false;

   public function dealItem()
   {
       return $this->belongsTo('App\SkyDealitem', 'deal_core_service_id', 'core_service_id');
   }
}

class SkyDealItem extends Model
{
protected $table = 'sky_deal_item';
public $timestamps = false;

public function daypart()
{
    return $this->belongsTo('App\Daypart','daypart_code_id','id');
}
}

class Daypart extends Model
{
protected $table = 'avt_US_daypart';
public $timestamps = false;

public function deals()
{
    return $this->hasMany('App\DealItem','daypart_code_id','id');
}
}

Every spot will have a column called pre_eval_tvr, it belongs to a DealItem and also to a campaign also

Every DealItem belongs to daypart.

FYI - A campaign will have multiple spots

Now the query which i am looking is daypart wise pre_eval_tvr using relationships.

Using just normal join query i can able to get it but with nested relationships i can't able to get it.

FYI - Join Query

select sum(avt_spot.pre_eval_tvr) as pre_eval_tvr, avt_US_daypart.* from   avt_spot inner join sky_deal_item on avt_spot.deal_core_service_id =  sky_deal_item.core_service_id inner join avt_US_daypart on  avt_US_daypart.id = sky_deal_item.daypart_code_id where avt_spot.allocated_to_campaign = 4442

group by avt_US_daypart.id;



via Chebli Mohamed

Missing pagination with Resource in CollectionResource

I'm trying to get a paginated CollectionResource after to use a Resource in collection, but the paginate data is always missing.

BillController :

$bill = Bill::with('category');    
return new BillCollectionResource( BillResource::collection($bill->paginate(10)) );

BillResource

public function toArray($request)
{   
    $data = parent::toArray($request);
    $data['lorem'] = 'ipsum';
    $data['foo'] = 'bar';
    return $data;
}

BillCollectionResource

public function toArray($request)
{
return [
    'data'                  => $this->collection,
    'rows_count'            => $rows_count,
    'total_balance'         => $total_balance,
    'total_num_debits'      => $total_num_debits,
    'total_num_credits'     => $total_num_credits,
    'total_balance_debits'  => $total_balance_debits,
    'total_balance_credits' => $total_balance_credits,

    ];
}

Expected results:

{
  data:                 [...],
  rows_count            : 16,
  total_balance         : 200.00,
  total_num_debits      : 8,
  total_num_credits     : 4,
  total_balance_debits  : -100.00,
  total_balance_credits : 100.00,

   links: 
    {
        first: 'http://localhost:8001/api/...',
        last:  'http://localhost:8001/api/...',
        next:  'http://localhost:8001/api/..',
        prev:  null,
    },
    meta: 
    {
        to:             5,
        from:           1,
        path:           'http://localhost:8001/api/...',
        total:          75
        per_page:       5,
        last_page:      15,
        current_page:   1,
    }

}

Current results:

{
  data:                 [...],
  rows_count            : 16,
  total_balance         : 200.00,
  total_num_debits      : 8,
  total_num_credits     : 4,
  total_balance_debits  : -100.00,
  total_balance_credits : 100.00,
}

I tried to add the pagination manually too, but all $request methods below are undefined.

BillCollectionResource

        'pagination' => 
         [
            'total'         => $request->total(),
            'count'         => $request->count(),
            'per_page'      => $request->perPage(),
            'current_page'  => $request->currentPage(),
            'total_pages'   => $request->lastPage()
         ]

What can be the reason behind this behaviour? Thanks in advance.



via Chebli Mohamed

Laravel ajax request in every row

@section('script')
    @foreach ($unit as $user)
        <script>
                $(document).ready(function(){
                    $('#case_number').keyup(function(){
                        var query = $(this).val();
                        if (query != ''){
                            var _token = $('input[name="_token"]').val();
                            $.ajax({
                                url:"",
                                method:"POST",
                                data:{query:query, _token:_token},
                                success:function(data){
                                    $('#case_number_list').fadeIn();
                                    $('#case_number_list').html(data);
                                }
                            })
                        }
                    });
                });
                $(document).on('click', 'li', function(){
                    $('#case_number').val($(this).text());
                    let y = $(this).val();
                    $('#case_number_hidden').attr('value', y);
                    $('#case_number_list').fadeOut();
                });
        </script>
    @endforeach
@endsection


How to make this loop in every row? Because if I leave it without the foreach it will only work on the first row of the table.

PS: foreach don't work



via Chebli Mohamed

Laravel: error "The page has expired due to inactivity" (419 unknown status)

I get the error The page has expired due to inactivity. Please refresh and try again. on a Laravel 5.6.39. In Chrome Network tab it says error login - 419 unknown status

I can reproduce the error following these steps:

  • go to login view
  • enter username and password and don't check "remember me" flag
  • wait that session expires (for test purpose I set SESSION_LIFETIME to 1 minute)
  • hit Login button and I get that error

I already read and tried the most common causes:

  • @csrf is present in the login form (it's the default authentication by Laravel)
  • the folder storage has 755
  • tried to launch php artisan cache:clear php artisan config:clear php artisan route:clear php artisan view:clear php artisan config:cache php artisan key:generate
  • I'm using the default SESSION_DRIVER=file but in production I also tried to replace it with SESSION_DRIVER=cookie with SESSION_DOMAIN=https://app.my-domain.com/

My .env file

APP_NAME='My App Name'
APP_ENV=local
APP_KEY=base64:+P6N350yBjAzw4q3oarQY/8mpJxDY7uwTTafriWrvMM=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=https://app.my-domain.com

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=xxx
DB_USERNAME=xxx
DB_PASSWORD=xxx

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=1
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=xxx
MAIL_PASSWORD=xxx
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

ITEMS_PER_PAGE=20
BIRTH_YEAR=2018

I really have no more idea to solve this. Some helps? Thanks



via Chebli Mohamed

Separate Redis database for testing in Laravel

I'm using Redis to store user-defined config for my Laravel app. I want to know how can I separate the Redis database is being used while testing from the one that is going to be used in for production? That's because I need to flush Redis before each test case and I don't want this to touch my data in main (production) Redis database.



via Chebli Mohamed

Laravel: QueryException could not find driver Centos 7 Linux Server

I have cloned Laravel app on Centos 7 Linux server. In user registration page, I got this error on submit button:

enter image description here

I tried running the following command but nothing changed:

sudo yum install php-mysql

enter image description here

so I run php -i, and I got:

enter image description here

Any ideas about fixing this error?



via Chebli Mohamed

Mysql trigger run manually but not triggered by laravel Model insert method

I have made a simple trigger to increase the count of attributeset when any product is assigned into it. It works well when i create new product. But problem is that it do not trigger when i use the Laravel save method to insert a record.

Here is my trigger



CREATE TRIGGER `after_insert_product_count_in_attribute_set` AFTER 
INSERT ON `sbn_product` FOR EACH ROW BEGIN update 
`sbn_attribute_set` SET product_usage = product_usage + 1 where id 
= New.attribute_set_id; END


Here is my laravel code



    $product = new Product();
    $product->url = $url;  
    $product->auto_sku = $autosku;
    $product->created_by = $user_id;
    $product->updated_by = $user_id; 
    $product->price=10.15
    $product->save();




via Chebli Mohamed

Log Laravel is publicly accessible

Okay, maybe I'm overlooking something. But we do have kind of a big problem. our Laravel log (storage/log/laravel.log) is publicly accessible.

The way people can access the log is when they go to domain.com/storage/log/laravel.log . I can't find a real solution but I'm sure this is a problem not everybody is facing. I hope someone can help me out.



via Chebli Mohamed

Get all objects that exist in two collections

I'm building a Laravel page on which I want to show a list of lessons. Which lessons should be on the page is filtered by three criterias (of which all should be true):

  1. The lesson is active, ie "where('active', true)". Simple enough.
  2. The lesson is part of a track that the user has chosen. Models are set up with belongsToMany() (it is a many-to-many relationship), so I can get these lessons by a simple $track->lessons.
  3. This is where it gets tricky. Some lessons should only be visible to users with certain titles (ie there is a many to many between titles and lessons). I can get the lessons with the correct title requirement using Auth::user()->title->lessons.

Question is how I get all this together. The best I've come up with this far is the following:

$title = Auth::user()->title;
$lessons = Lesson::where('active', true)
    ->whereIn('id', $track->lessons->pluck('id'))
    ->where(function ($query) use($title) {
      $query->whereIn('id', $title->lessons->pluck('id'))->orWhere('limited_by_title', false);
    })
    ->get();

...which is crap ugly, clearly suboptimal and (for some reason I reallly don't understand) also won't work (I don't get the lessons my title entitles me to in my list). Been struggling for quite some hours now, I get the feeling that I'm overcomplicating, first plucking id's and then using them in a whereIn() can't possibly be a good way of doing this.

So I can easily enough get a collection of lessons in the track, and I can get a collection of lessons belonging to the title, but how do I get all objects that exist in both those collections?



via Chebli Mohamed

Why laravel 5.7 basic route redirect to 404?

i have install fresh laravel 5.7. now when i declare route in web.php. when i declare like

Route::get('foo', function () {
    return 'Hello World';
});

it redirect to 404 page but.. when i declare my root directory name along with route just like

Route::get('blog/foo', function () {
    return 'Hello World';
});

it shows me expected result..

but i don't want to define like that. i want to define like this and get the expected result

  Route::get('foo', function () {
        return 'Hello World';
    });

help me !



via Chebli Mohamed

mercredi 30 janvier 2019

hello, i'm having trouble running a react-navigation on react-native and redux

I have this code that connects laravel with react-native, it works with a container (LoginContainer) that contains the functions that are applied on the screen (LoginScreen).

https://github.com/VientoDigital/ReactNativeLaravelLogin

How can I make the view show using react-navigation? try to place the LoginContainer as a screen in the function createStackNavigator, but it does not work, I'm sure that a way to do it with state, reducers, etc, but I'm new with these technologies, if you can enlighten me the way I would thank you very much. regards



via Chebli Mohamed

the server responded with a status of 500 (Internal Server Error) in laravel 5.7

why 500 (Internal Server Error)?

my route for upload image

Route::post('tech-img', 'ImageController@imageCropPost');

My Controller for upload image

public function imageCropPost(Request $request)
{
    $data = $request->image;
    $id=$request->id;

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);


    $data = base64_decode($data);
    $image_name= time().'.png';
    $path = public_path() . "/upload/" . $image_name;
    file_put_contents($path, $data);
    $update=DB::table('technologys')
    ->where('id','=', $id)
    ->update(['img' => $image_name]);return $update;}`

My Ajax for upload image

function uptecimage(id){
var id=id.id;
$('#inputimg').val(id);}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});

$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
    type: 'canvas',
    size: 'viewport'
}).then(function (resp) {
   var id= document.getElementById('inputimg').value;
    $.ajax({
        url: "/tech-img",
        type: "POST",
        data: {"image":resp, "id":id},
        success: function (data) {
            console.log(data);
            /*
            html = '<img src="' + resp + '" />';
            $("#upload-demo-i").html(html);
            */
        }
    });
}); 
});

My blade Templet OR HTML code for upload image

<button data-toggle="modal" href='#upimage' onclick="uptecimage(this)" id=""><i class="fa fa-camera"></i></button>

<div class="modal fade" id="upimage">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title">Image Upload</h4>
                        </div>
                        <div class="modal-body">

                        <input type="hidden" name="inputimg" id="inputimg" class="form-control" value="">

                        <div id="upload-demo" style="width:350px"></div>
                        <strong>Select Image:</strong>
                    <br/>
                    <input type="file" id="upload">
                    <br/>
    <button class="btn btn-success upload-result">Upload Image</button>
                        </div>

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

When press Upload Image button then error Failed to load resource: the server responded with a status of 500 (Internal Server Error)



via Chebli Mohamed

How do I use Laravel Backpack fields in a custom view?

Laravel Backpack gives a clean function to use its fields in its crud forms. I'd like to use the same built-in fields in a custom view.



via Chebli Mohamed

Laravel Query to get distinct values on a column, but after using orderby to get latest distinct values

I want to show only distinct rows from a table, but those values needs to be the latest ones, which I am filtering from date in the table. Here is my query. the result I am getting is the older row from date, the orderby is not working here I guess. please help. I have attached my table.

$reports= DB::table('resident_assessment')->where('resident_assessment.assessment_date','<=',$date)->join('assessment_entry','resident_assessment.assessment_id','=','assessment_entry.assessment_id')->orderby('resident_assessment.assessment_date','desc')->distinct()->get();

enter image description here



via Chebli Mohamed

different result laravel and cli postgresql

I have the following script/query in Laravel,

$q = "SELECT COUNT(*) AS lembar, SUM(r.worth) AS jumlah
FROM receipts r
JOIN customers c ON c.id=r.customer_id
JOIN customer_types ct ON ct.code=c.customer_type_code
WHERE r.print_date BETWEEN ? and ? and c.kelurahan=? AND ct.code IN(?)";


$group = ['Q', 'R', 'S'];
$g = join('/', $group);
$g_in = join("','", $group);


$x = new \stdClass;
$x->group = $g;
$x->result = \DB::select(\DB::raw($q), [
    $start_date,
    $end_date,
    $kel->kelurahan, // "KEBON PISANG"
    $g_in
]);

the query works well in PgAdmin, but in Laravel it's return 0, null. also when $kel->kelurahan change to something else it works on Laravel too.



via Chebli Mohamed

Three way pivot table get all teams a user belongs to and the roles for each team

I am using a belongsToMany relationship between users, teams, and the roles tables.

What I want to do is get all teams that an authenticated user belongs too and get all of the roles the user has for that team under. Then I want to output the it to JSON. (I'm not using blade).

User Frank:

Team 1:

  • Manager
  • Player

Team 2:

  • Manager

Team 5:

  • Player

Query output to show relations

return User::first(1)->with('teams','roles')->get();

Output:

{  
   "id":1,
   "username":"Frank",
   "name":"Frank",
   "email":"frank@example.com",
   "teams":[  
      {  
         "id":21,
         "name":"Team 1",
         "pivot":{  
            "user_id":1,
            "team_id":21,
            "role_id": 1
         }
      },
      {  
         "id":1,
         "name":"Team 2",
         "pivot":{  
            "user_id":1,
            "team_id":1,
            "role_id":1
         }
      },
      {  
         "id":3,
         "name":"Team 5",
         "pivot":{  
            "user_id":1,
            "team_id":3
            "role_id":2
         }
      }
   ],
   "roles":[  
      {  
         "id":1,
         "name":"Manager",
         "pivot":{  
            "user_id":1,
            "role_id":1,
            "team_id":21
         }
      },
      {  
         "id":2,
         "name":"Player",
         "pivot":{  
            "user_id":1,
            "role_id":2,
            "team_id":21
      },
      {  
         "id":1,
         "name":"Manager",
         "pivot":{  
            "user_id":1,
            "role_id":1,
            "team_id":1
         }
      },
      {  
         "id":2,
         "name":"Player",
         "pivot":{  
            "user_id":1,
            "role_id":2,
            "team_id":3
         }
      }
   ]
}



via Chebli Mohamed

sort laravel eloquent by custom (appended) attribute

I have a model with a custom attribute like this

    public function getOpenStatusAttribute()
    {
        //some logic...
        //returns '1-order' or '2-pre-order' or '3-closed'
    }

Now i want to sort the collection in the eloquent query. I use order by name etc.. those are columns in the table but i want to order it by the custom attribute first, and then by name etc..

is it possible to do this in the query? or do i have to loop the collection and do some resorting ?



via Chebli Mohamed

How to get value Auth::User() array elements in Laravel

I want to get elements in Auth::User() Array in page.Blade.php. After .output array show many elements like

  Admin {#474 ▼
  #guard: "admin"
  #fillable: array:4 [▶]
  #hidden: array:2 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []

I'm trying to access using Auth::user()->guard; this but it's not work for me . please tell me how to get this.Many Thanks in Advance.



via Chebli Mohamed

How to debug Laravel Site show HTTP ERROR 500?

I'm on Laravel 5.7, and my app loading fine on my local Mac OSX.

But on my production Ubuntu Server, I kept getting 500


permissions

I've already chmod R 777 storage/ bootstrap/ vendor/


.env

I also check my .env file, everything seem to be in place proper configured.


nginx

I checked in cd /var/log/nginx/ I see nothing there.


laravel

I checked /home/forge/bheng/storage/logs - nothing there also.


Questions

How would one go about and debug this further ?


I'm open to any suggestions at this moment.

Any hints/suggestions / helps on this be will be much appreciated!



via Chebli Mohamed

how to compile js to es5 with laravel mix?

I have laravel Vue app and it works perfectly with chrome and firefox. but it doesn't work on Edge or IE11 and the console shows error on arrow function!? How to compile or transpile to es5 with laravel mix and webpack? could you show the correct configuration for webpack.mix.js? tnx alot



via Chebli Mohamed

laravel custom validation rule when updating record

I have 2 tables for Series and Lessons in lessons Model I have relation to relate lesson to a series, I created a custom validation rule to prevent the same episode_number in the lessons table to be repeated in the same series and it works fine but when updating I want to exclude this lesson from being checked This is my table of lessons

public function up()
{
    Schema::create('lessons', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('series_id');
        $table->string('title');
        $table->text('description');
        $table->unsignedInteger('episode_number');
        $table->unsignedInteger('video_id')->unique();
        $table->boolean('premium')->default(0);
        $table->timestamps();

        $table->unique(['series_id', 'episode_number']);
    });
}

and this is the eloquent relation function in lessons model

public function series()
{
    return $this->belongsTo(Series::class);
}

and here is my custom validation rule

<?php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class uniqueSeriesLessonValidation implements Rule
{
public $id;
/**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($id)
{
    $this->id = $id;
}

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    $count = DB::table('lessons')->where('episode_number', $value)
        ->where('series_id', $this->id)
        ->count();

    if ($count === 0){
        return true;
    }

    return false;

}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'The lesson title should not be repeated in the same series twice.';
}
}

and this is my validation when creating new lesson which works fine to prevent duplicate of episode_number of a lesson in the same series twice

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id)],
        'video_id' => 'required|unique:lessons|numeric'
    ];
}

and this is my validation when updating lesson which I have the problem

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id),$request->lesson->id],
        'video_id' => 'required'
    ];
}



via Chebli Mohamed

i am using laravel 5.5 i want to use CrondJobs But none of my classes found in my php file

//This Is My Name Space
namespace App\Http\Controllers\Crons;

//Using Jalali but Class Not Found
    $date =\Morilog\Jalali\Jalalian::now()->format("Y/m/d " ) ;

//this is my erro in my error_log

//PHP Fatal error: Uncaught Error: Class 'Morilog\Jalali\Jalalian' not found in /home/micacoco/crons/cron.php:29



via Chebli Mohamed

I need to use Laravel Passport authentication for micro services running across multiple servers and domains,

I have micro services running across multiple servers and domains, I need them all to authenticate to one server, I am using Laravel Passport for my API authentication, the "Laravel\Passport\Passport::scopesFor(['place-orders', 'check-status']);" is vital to my service since it will limit the times consumer need to authenticate and check access level.

what is the best way to go about doing something like this.



via Chebli Mohamed

Run ZSH command from Laravel

After sending an email, I need to move an entire folder to another server which is our archive.

I am trying this but it does nothing

$randie = '1548863958';
$src = "/var/www/forms_farm/storage/app/public/qrf/{$randie}";
$dest = "/var/www/file_store/qrf/{$randie}";

exec("mv {$src} {$dest}");



via Chebli Mohamed

Laravel 5 composer tags package with optional custom fields. Which package would you recommend?

I need a tags package with ability of adding custom fields to tag, for example "color", or other ones.

What are you using usually if you need more flexible implementation? Thanks in advance for each comment!



via Chebli Mohamed

Laravel Eloquent - Get a record every hour

I have a table that stores statistics every 3 minutes with a cron job. I want to display a chart with this data but I want the chart to have an interval of 1 hour otherwise it looks ugly as hell and is too much resource demanding. The table has the created_at and updated_at columns.

How can I do this with eloquent?

Thanks for your help!



via Chebli Mohamed

Getting HTTP 419 requesting on iphone app

I developed a login endpoint for the api that I am working on and have been testing this endpoint with postman. Once I finished I tested it with postman and received a 200 success message. After integrating this into my app using Alamofire I did not get the same message back. Instead I got a 419. Upon further inspection on other topics I found that this is due to no csrf token in my request, but I do not have one in my postman request. Not sure what is going on but any help would be great.

public function login(LoginRequest $request){
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return Auth::user();
        }
    }

POST /api/v1/login?email=test@test.com&amp; password=123456 HTTP/1.1
Host: mysite.com
Accept: application/json
cache-control: no-cache



via Chebli Mohamed

How to fix error including autoNumeric to laravel / blade / jQuery / Bootstrap project?

I try to install autoNumeric from https://www.jqueryscript.net/demo/Easy-Numbers-Currency-Formatting-Plugin-autoNumeric/

In my laravel 5.7/ blade / jQuery v3.3.1 / Bootstrap v4.1.2 app and for this in my blade form where I want to use autoNumeric I included ref to AutoNumeric.js file:

...
@endsection

@section('scripts')

    <link rel="stylesheet" href="" type="text/css">
    <link rel="stylesheet" href="" type="text/css">
    <script src=""></script>

    <script src=""></script>

    <script src="?dt="></script>
...

I uploaded 8 files into /public/js/AutoNumeric subdirectory from /autoNumeric-master/src of uploaded zip file

and when jquery is inited I added line :

$('#selling_range').autoNumeric('init');

and I got error :

Uncaught SyntaxError: Unexpected identifier

and clicking on the error I see next error code:

https://imgur.com/a/mQ3henJ

Is it wrong way of including this library and which is valid ?

Thanks in advance!



via Chebli Mohamed

Laravel middleware is "bypassed" when i submit the invalid token, but when it is a valid token, the middleware is executed

all my fellow friends, i have a question.

Route::group([
    'middleware' => ['ensure.role:store', 'auth:api']
]

For simplification,

i have two roles : ADMIN and STORE

I have created a middleware that will validate user role, and if the user role is correct, then will allow the user to access the route.

It works fine. I tried using ADMIN Jwt Token to access STORE routes, and rightfully i am kicked out, and vice versa.

But now, if i modify the token, lets say i add a string to any part of the token, and try to access any route, actually i am allowed to.

I tried var_dump and print something on the related middleware, and here are my observation.

1. If the token is VALID as one of the user role, then 
the var_dump is executed, (means the middleware is executed)
2. if the token is INVALID as in i add / modify the original
token, then the var_dump is not executed, and so are the 
others route middleware.

I am wondering what causes this behavior, and what could be the fix for this issue, as i need to throw 401 unauthenticated in any token invalid case.

Thank you



via Chebli Mohamed

Laravel QueryBuilder where clause with user info on other model

I have a Model ImageRequest that is related to my User model like this:

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

An my User model like this:

public function imageRequests()
{
    return $this->hasMany('App\ImageRequest');
}

Now I use this package to build my filterable query to fetch all ImageRequests:

spatie/laravel-query-builder

this is what my query looks like:

$query = QueryBuilder::for(ImageRequest::class)
        ->with(['requestTypes'])
        ->allowedIncludes('requestTypes')
        ->orderByRaw("FIELD(status , 'new') desc")
        ->orderBy('functional_id', 'asc')
        ->allowedFilters(
            'id',
            'pv_number',
            'created_at',
            Filter::scope('starts_between'),
            'location_of_facts',
            'train_nr',
            'status',
            'result_of_search',
            Filter::custom('type', RequestTypeFilter::class)
);

I need to add a where clause for the User model something like this:

->where('zone', Auth::user->zone);

But it says:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'zone' in 'where clause' (SQL: select count(*) as aggregate from image_requests where zone = a)



via Chebli Mohamed

View [] not found

** The error log is: View [] not found. (View: /work/prj/resources/views/emails/notifyTest.blade.php) {"exception":"[object] (ErrorException(code: 0): View [] not found. (View: /work/prj/resources/views/emails/notifyTest.blade.php) at /work/php/arousal-service-common/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php:137, InvalidArgumentException(code: 0): View [] not found. at /work/php/arousal-service-common/vendor/laravel/framework/src/Illuminate/View/FileViewFinder.php:137)

I try to send an email like this:

$mail = new \App\Email\NotifyEmail(
                'Title',
                'content');
            $mail->onQueue('email');
            \Mail::to($email)->queue($mail);

$mail = new \App\Email\NotifyEmail(
                'name',
                'gender');
            $mail->onQueue('email');
            \Mail::to($email)->queue($mail);


public function build()
    {
        return $this->subject("this is test notification email")
            ->markdown(
                'emails.notifyTest',
                [
                    'name'   => $this->name,
                    'gender' => $this->currency,
                ]
            );
    }

How to solve this problem, **



via Chebli Mohamed

Not Showing user avatar

HTML tag

<img src="storage/app/avatars/23_avatar1548246815.bmp" alt="">

File already exist on this path. But not showing. And I used also this php artisan storage:link, but not working.



via Chebli Mohamed

PHP's json extension is required to use Monolog's NormalizerFormatte

iam upolading my app on cpanel and i got this error PHP s json extension is required to use Monologs NormalizerFormatte



via Chebli Mohamed

Laravel observer Update Event in not Triggering

i am trying to update my remaining_quantity by decreasing the checked_out_quantity from the initial Quantity like this but its not working

public function updating(Consumable $consumable)
{
    $consumable->remaining_qty = $consumable->quantity - $consumable->checked_out_qty;
    $consumable->save();     
}   

anybody know how i can get it to trigger?



via Chebli Mohamed

How to send email from multiple users to multiple users in laravel 5.7

I am making a site where people room owners upload their room for rent with their name and email Customers can come and see the room and send email to the room owner with their message from the site by filling up a forom which consist of Email , Name and your Message I dont know how to write that mail function I tried but failed If any one can help me plz ....



via Chebli Mohamed

Trying to do multi auth using spatie laravel-permissions hasRoles

I am using Spatie Laravel Permissions to manage the permissions in my project and I am trying to use the hasRole() function for multi auth. I am using if conditions to redirect users to different pages. And its not working So Does some one have idea how to use spatie laravel permissions package to do multiauth.



via Chebli Mohamed

Laravel model object date value changed when print

I use Laravel framework and I have a strange issue, when I dump model object it return a true results for attributes:

@extends('frontend.includes.master')
@section('content')

<?php
dump($row); exit;
?>
<main class="main">
    <section class="banner banner--inner banner--short">
        <div class="container">

enter image description here

but when I dump or print the date value it give me a wrong result:

<?php
dump($row->start_date); exit;
?>

enter image description here

also this happen when I dump from view, but when I dump from controller it give me a true result:

$row = Forsah::with('company')->with('category')->with('region')->where('forsah.id', $id)->first();
        $data['row'] = $row;


        $data['user_forsah'] = false;
        if (Session::get('member_id')) {
            $user_forsah_row = UsersForsah::where('user_id', Session::get('member_id'))->where('forsah_id', $id)->first();
            if ($user_forsah_row) {
                $data['user_forsah'] = true;
            }
        }

        dump($row->start_date); exit;
        return view('frontend.forsah.show', $data);

enter image description here



via Chebli Mohamed

FullCalendar switch events by user in vuejs

I have configured fullcalendar in vuejs, events of 3 members now i want to show hide users events on click.

Normal jQuery working perfect but i am new on vuejs so don't have idea how to do that.

$('#mycalendar').fullCalendar({
    events: [
        {
            title: 'Event 1',
            start: '2015-05-01',
            school: '1'
        },
        {
            title: 'Event 2',
            start: '2015-05-02',
            school: '2'
        },
        {
            title: 'Event 3',
            start: '2015-05-03',
            school: '1'
        },
        {
            title: 'Event 4',
            start: '2015-05-04',
            school: '2'
        }
    ],
    eventRender: function eventRender( event, element, view ) {
        return ['all', event.school].indexOf($('#school_selector').val()) >= 0
    }
});

$('#school_selector').on('change',function(){
    $('#mycalendar').fullCalendar('rerenderEvents');
})



via Chebli Mohamed

How to check for a string against json encode array in a table in Laravel?

I am having an issue with a Laravel project. I have a few checkbox of computer specification which I want to check against the database field that I am having called tech_specs. This tech_specs field contains the serialize array of all the tech_specs that are available for that specific product. I just want to list out the products having that particular specification. Please let me know how to proceed.

Controller Function

public function GetPage(Request $request,$page_slug){

        $page_title=self::replaceAll($page_slug);
        $category_level1_id=null;
        $category_level2_id=null;
        $category_level3_id=null;
        $products=null;
        $products_count=null;
        $product_lookup=null;
        $page_breadcrumb=null;
        $product_type=null;
        $brand=null;
        $final_selected_brand=array();
        $tech_specs_filter=null;
        $specs_filters=null;

        //Sorting Vars
        $sort_by=$request->query('sort_by');
        $min_price=$request->query('min_price');
        $max_price=$request->query('max_price');

        //Filter Vars
        $product_condition=$request->query('product_condition');
        $product_brand=$request->query('brand');
        $is_assured=$request->query('assured');
        $is_cod_allowed=$request->query('cod');
        $product_specs=$request->query('tech_spec');


        $final_selected_brand=null;
        if(!empty($product_brand)){
            $final_selected_brand=explode('|',$product_brand);
        }

        $final_selected_brand_ids=null;
        if(!empty($final_selected_brand)){
            foreach($final_selected_brand as $fsb){
                $final_selected_brand_ids[]=self::GetBrandIDFromName($fsb);
            }
        }

        $final_selected_spec=null;
        if(!empty($product_specs)){
            $final_selected_spec=explode('|',$product_specs);
        }

        // Get the categories
        $getCatlvl1 = Category::whereCategorySlug($page_slug);
        $getCatlvl2 = SubCategory::whereCategorySlug($page_slug);
        $getCatlvl3 = SubCategoryLvl3::whereCategorySlug($page_slug);


        //Check if is category level 1
        if ($getCatlvl1->count()) {
            $category_level1_id = $getCatlvl1->pluck('id')->toArray();
            $product_type = $getCatlvl1->pluck('product_type')->toArray()[0];
            $category_level1_name = $getCatlvl1->pluck('category_name')->toArray()[0];

            $brand=Brand::where('product_type',$product_type)->orderBy('brand_name')->get();

            $category_level2_id = SubCategory::where('parent_category', $category_level1_id)
                ->pluck('id')
                ->toArray();

            $category_level3_id = SubCategoryLvl3::whereIn('parent_category', $category_level2_id)
                ->pluck('id')
                ->toArray();

            $product_lookup = DB::table('products')
                                ->where('is_approved','Yes')
                                ->where('category_level',3)
                                ->whereIn('category',$category_level3_id)
                                ->when($product_condition, function($query) use($product_condition){
                                    $query->where('product_condition', $product_condition);
                                })
                                ->when($is_assured, function($query) use($is_assured){
                                    $query->where('is_assured','Yes');
                                })
                                ->when($is_cod_allowed, function($query) use($is_cod_allowed){
                                    $query->where('merchant_allowed_for_cod','Yes');
                                })
                                ->when($final_selected_brand_ids, function($query) use($final_selected_brand_ids) {
                                    if(count($final_selected_brand_ids)>1){
                                        $query->whereIn('brand',$final_selected_brand_ids);
                                    } else {
                                        $query->where('brand',$final_selected_brand_ids[0]);
                                    }
                                })
                                ->when($min_price and $max_price, function($query) use($min_price, $max_price) {
                                    if($min_price=='+50000'){
                                        $query->where('selling_price','>=',$min_price);
                                        $query->where('selling_price',$max_price);
                                    } else if($max_price=='+50000'){
                                        $query->where('selling_price',$min_price);
                                        $query->where('selling_price','>=',$max_price);
                                    } else {
                                        $query->whereBetween('selling_price', [
                                            $min_price,
                                            $max_price
                                        ]);
                                    }
                                })
                                ->when($sort_by, function($query) use($sort_by) {
                                    if($sort_by=='high-price'){
                                        $query->orderBy('selling_price', 'DESC');
                                    }
                                    if($sort_by=='low-price'){
                                        $query->orderBy('selling_price', 'ASC');
                                    }
                                    if($sort_by=='new-arrivals'){
                                        $query->orderBy('id', 'DESC');
                                    }
                                });

            $page_breadcrumb.= '<li class="breadcrumb-item active" aria-current="page">'.$category_level1_name.'</li>';
        }

        //Check if is category level 2
        if ($getCatlvl2->count()) {

            $category_level2_id = $getCatlvl2->pluck('id')->toArray();
            $product_type = $getCatlvl2->pluck('product_type')->toArray()[0];
            $category_level2_name = $getCatlvl2->pluck('category_name')->toArray()[0];

            $brand=Brand::where('product_type',$product_type)->orderBy('brand_name')->get();

            $parent_id = $getCatlvl2->pluck('parent_category')->toArray()[0];
            $get_cat_parent_id = Category::where('id',$parent_id)->get()->toArray()[0];
            $category_level1_name = $get_cat_parent_id['category_name'];
            $category_level1_link = $get_cat_parent_id['category_slug'];

            $category_level3_id = SubCategoryLvl3::whereIn('parent_category', $category_level2_id)
                ->pluck('id')
                ->toArray();

            $product_lookup = DB::table('products')
                ->where('is_approved','Yes')
                ->where('category_level',3)
                ->whereIn('category',$category_level3_id)
                ->when($product_condition, function($query) use($product_condition){
                    $query->where('product_condition', $product_condition);
                })
                ->when($is_assured, function($query) use($is_assured){
                    $query->where('is_assured','Yes');
                })
                ->when($is_cod_allowed, function($query) use($is_cod_allowed){
                    $query->where('merchant_allowed_for_cod','Yes');
                })
                ->when($final_selected_brand_ids, function($query) use($final_selected_brand_ids) {
                    if(count($final_selected_brand_ids)>1){
                        $query->whereIn('brand',$final_selected_brand_ids);
                    } else {
                        $query->where('brand',$final_selected_brand_ids[0]);
                    }
                })
                ->when($min_price and $max_price, function($query) use($min_price, $max_price) {
                    if($min_price=='+50000'){
                        $query->where('selling_price','>=',$min_price);
                        $query->where('selling_price',$max_price);
                    } else if($max_price=='+50000'){
                        $query->where('selling_price',$min_price);
                        $query->where('selling_price','>=',$max_price);
                    } else {
                        $query->whereBetween('selling_price', [
                            $min_price,
                            $max_price
                        ]);
                    }
                })
                ->when($sort_by, function($query) use($sort_by) {
                    if($sort_by=='high-price'){
                        $query->orderBy('selling_price', 'DESC');
                    }
                    if($sort_by=='low-price'){
                        $query->orderBy('selling_price', 'ASC');
                    }
                    if($sort_by=='new-arrivals'){
                        $query->orderBy('id', 'DESC');
                    }
                });

            $page_breadcrumb.= '<li class="breadcrumb-item"><a href="'.url('/').'/'.$category_level1_link.'">'.$category_level1_name.'</a></li>';
            $page_breadcrumb.= '<li class="breadcrumb-item active">'.$category_level2_name.'</li>';

        }

        //Check if is category level 3
        if ($getCatlvl3->count()) {
            $category_level3_id = $getCatlvl3->pluck('id')->toArray();
            $product_type = $getCatlvl3->pluck('product_type')->toArray()[0];
            $category_level3_name = $getCatlvl3->pluck('category_name')->toArray()[0];

            $brand=Brand::where('product_type',$product_type)->orderBy('brand_name')->get();

            $matchThese=["product_type"=>$product_type,"category"=>$category_level3_id,"category_level"=>3];
            $tech_specs_filter=TechSpecsFilter::where($matchThese)->get()->toArray();

            if(!empty($tech_specs_filter)){
                $temp=$tech_specs_filter[0];
                $specs_filters=json_decode($temp['filter_specs']);
            }

            $parent_id_lvl2 = $getCatlvl3->pluck('parent_category')->toArray()[0];
            $get_cat_parent_id_lvl2 = SubCategory::where('id',$parent_id_lvl2)->get()->toArray()[0];

            $category_level2_name = $get_cat_parent_id_lvl2['category_name'];
            $category_level2_link = $get_cat_parent_id_lvl2['category_slug'];

            $get_cat_parent_id = Category::where('id',$get_cat_parent_id_lvl2['parent_category'])->get()->toArray()[0];
            $category_level1_name = $get_cat_parent_id['category_name'];
            $category_level1_link = $get_cat_parent_id['category_slug'];

            $product_lookup = DB::table('products')
                ->where('is_approved','Yes')
                ->where('category_level',3)
                ->whereIn('category',$category_level3_id)
                ->when($product_condition, function($query) use($product_condition){
                    $query->where('product_condition', $product_condition);
                })
                ->when($is_assured, function($query) use($is_assured){
                    $query->where('is_assured','Yes');
                })
                ->when($is_cod_allowed, function($query) use($is_cod_allowed){
                    $query->where('merchant_allowed_for_cod','Yes');
                })
                ->when($final_selected_brand_ids, function($query) use($final_selected_brand_ids) {
                    if(count($final_selected_brand_ids)>1){
                        $query->whereIn('brand',$final_selected_brand_ids);
                    } else {
                        $query->where('brand',$final_selected_brand_ids[0]);
                    }
                })
                /*->when($final_selected_spec, function($query) use($final_selected_spec) {
                    if(count($final_selected_spec)>1){
                        //$query->whereIn('brand',$final_selected_spec);
                    } else {
                        $query->where('brand',$final_selected_spec[0]);
                    }
                })*/
                ->when($min_price and $max_price, function($query) use($min_price, $max_price) {
                    if($min_price=='+50000'){
                        $query->where('selling_price','>=',$min_price);
                        $query->where('selling_price',$max_price);
                    } else if($max_price=='+50000'){
                        $query->where('selling_price',$min_price);
                        $query->where('selling_price','>=',$max_price);
                    } else {
                        $query->whereBetween('selling_price', [
                            $min_price,
                            $max_price
                        ]);
                    }
                })
                ->when($sort_by, function($query) use($sort_by) {
                    if($sort_by=='high-price'){
                        $query->orderBy('selling_price', 'DESC');
                    }
                    if($sort_by=='low-price'){
                        $query->orderBy('selling_price', 'ASC');
                    }
                    if($sort_by=='new-arrivals'){
                        $query->orderBy('id', 'DESC');
                    }
                });

            $page_breadcrumb.= '<li class="breadcrumb-item"><a href="'.url('/').'/'.$category_level1_link.'">'.$category_level1_name.'</a></li>';
            $page_breadcrumb.= '<li class="breadcrumb-item"><a href="'.url('/').'/'.$category_level2_link.'">'.$category_level2_name.'</a></li>';
            $page_breadcrumb.= '<li class="breadcrumb-item active">'.$category_level3_name.'</li>';
        }

        $temp_products =  $product_lookup->get();

        if(count($temp_products)>0){
            $products_count = $product_lookup->get()->count();
            $products = $product_lookup->paginate(50);
        }

        //Category Tree
        $content='<ul class="category-page-tree">';
        $get_category_tree_cat_level1 = Category::orderBy('category_name')->get();
        foreach($get_category_tree_cat_level1 as $gct1){
            $content.='<li>';
                $content.='<a href="'.url('/').'/'.$gct1->category_slug.'" class="level1_cat_color"><i class="fas fa-angle-right"></i> '.$gct1->category_name.'</a>';
                $get_category_tree_cat_level2 = SubCategory::orderBy('category_name')
                    ->where('parent_category',$gct1->id)
                    ->get();
                $content.='<ul>';
                    foreach($get_category_tree_cat_level2 as $gct2){
                        $content.='<li>';
                            $content.='<a href="'.url('/').'/'.$gct2->category_slug.'" class="level2_cat_color"><i class="fas fa-angle-right"></i> '.$gct2->category_name.'</a>';
                            $get_category_tree_cat_level3 = SubCategoryLvl3::orderBy('category_name')
                                ->where('parent_category',$gct2->id)
                                ->get();
                            $content.='<ul>';
                            foreach($get_category_tree_cat_level3 as $gct3){
                                $content.='<li>';
                                $content.='<a href="'.url('/').'/'.$gct3->category_slug.'" class="level3_cat_color"><i class="fas fa-angle-right"></i> '.$gct3->category_name.'</a>';
                                $content.='</li>';
                            }
                            $content.='</ul>';
                        $content.='</li>';
                    }
                $content.='</ul>';
            $content.='</li>';
        }
        $content.='</ul>';


        return view("frontend.pages.category_page")->with(
            array(
                'products'=>$products,
                'products_count'=>$products_count,
                'page_slug'=>$page_slug,
                'page_breadcrumb'=>$page_breadcrumb,
                'product_type'=>$product_type,
                'brands'=>$brand,
                'page_title'=>$page_title,
                'category_tree'=>$content,
                'category_level_column'=>2,
                'min_price'=>$min_price,
                'max_price'=>$max_price,
                'selected_brand'=>(array)$final_selected_brand,
                'is_assured'=>$is_assured,
                'is_cod_allowed'=>$is_cod_allowed,
                'specs_filters'=>$specs_filters,
                'selected_specs'=>(array)$final_selected_spec,
            )
        );
    }

jQuery Code

$(document).on("click", ".tech_specs_filter_box input[type='checkbox']", function(e) {
        var selected_specs=$(this).val();
        var current_url=window.location.href;
        var page_slug=$("#page_slug").val();
        var url_parameters = [];
        var specs_append = [];

        //Parameters
        var product_condition = getParam('product_condition');
        var sort_by = getParam('sort_by');
        var min_price = getParam('min_price');
        var max_price = getParam('max_price');
        var brand = getParam('brand');
        var tech_spec = getParam('tech_spec');
        var to_add_quesion_mark='no';

        if($(this).prop("checked") == true){
            if(current_url.indexOf('?tech_spec') == -1){
                url_parameters.push('?tech_spec='+selected_specs);
            } else {
                if(current_url.indexOf('?tech_spec') !== -1){
                    specs_append.push('?tech_spec='+tech_spec);
                    specs_append.push('|'+selected_specs);
                    url_parameters.push(specs_append.join(""));
                } else if(current_url.indexOf('&tech_spec') !== -1){
                    specs_append.push('&tech_spec='+tech_spec);
                    specs_append.push('|'+selected_specs);
                    url_parameters.push(specs_append.join(""));
                } else if(current_url.indexOf('&tech_spec') !== -1) {
                    url_parameters.push('&tech_spec='+selected_specs);
                }
            }
        } else if($(this).prop("checked") == false) {

            var specsArr = [];
            $('.tech_specs_filter_box input:checked').each(function(index) {
                var temp_val=$(this).attr('id');
                specsArr.push($("#"+temp_val).val());
            });
            var getSpecStr = specsArr.join("|");

            if(getSpecStr!==""){
                if(current_url.indexOf('?tech_spec') !== -1){
                    url_parameters.push('?tech_spec='+getSpecStr);
                }
            } else {
                to_add_quesion_mark="yes";
            }
        }


        if(sort_by!==""){
            url_parameters.push('sort_by='+sort_by);
        }
        if(product_condition!==""){
            url_parameters.push('product_condition='+product_condition);
        }
        if(min_price!==""){
            url_parameters.push('min_price='+min_price);
        }
        if(max_price!==""){
            url_parameters.push('max_price='+max_price);
        }
        if(brand!==""){
            url_parameters.push('brand='+brand);
        }

        if(to_add_quesion_mark=='yes'){
            for(var i=0;i<url_parameters.length;i++){
                if(i==0) url_parameters[i] = '?'+url_parameters[i];
            }
        }

        target_location = url_parameters.join("&");
        window.location = page_slug+target_location;

    });

HTML View Tech Specs For the particular category that I have selected



via Chebli Mohamed

mardi 29 janvier 2019

How can I fetch from multi level array in Laravel eloquent?

My question is about fetching data from multi level array what is generated from Laravel Groupby method ( Eloquent) .

-array

array:1 [▼
  1 => array:3 [▼
    4 => array:1 [▼
      2 => array:7 [▼
        0 => array:7 [▶]
        1 => array:7 [▶]
        2 => array:7 [▶]
        3 => array:7 [▶]
        4 => array:7 [▶]
        5 => array:7 [▶]
        6 => array:7 [▶]
      ]
    ]
    3 => array:1 [▼
      1 => array:1 [▼
        0 => array:7 [▶]
      ]
    ]
    2 => array:1 [▼
      1 => array:1 [▼
        0 => array:7 [▶]
      ]
    ]
  ]
]


Actually my datatable is so-

{"4":{"2":[{"id":1,"technology_id":1,"subject_id":20,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":2,"technology_id":1,"subject_id":23,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":3,"technology_id":1,"subject_id":24,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":4,"technology_id":1,"subject_id":45,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":5,"technology_id":1,"subject_id":46,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":6,"technology_id":1,"subject_id":47,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"},{"id":7,"technology_id":1,"subject_id":48,"session_id":4,"semester_id":2,"created_at":"2019-01-18 18:16:49","updated_at":"2019-01-18 18:16:49"}]},"3":{"1":[{"id":8,"technology_id":1,"subject_id":1,"session_id":3,"semester_id":1,"created_at":"2019-01-18 18:18:27","updated_at":"2019-01-18 18:18:27"}]},"2":{"1":[{"id":9,"technology_id":1,"subject_id":7,"session_id":2,"semester_id":1,"created_at":"2019-01-18 18:18:27","updated_at":"2019-01-18 18:18:27"}]}}

I expect view in html is so-

https://imgur.com/a/O03Iog0

Can anyone help?



via Chebli Mohamed

How to reduce the product stock when the item is used

This is my 1st table

public function up()
    {
        Schema::create('perbaikans', function (Blueprint $table) {
            $table->increments('id_perbaikan');
            $table->string('nomor_dokumen_perbaikan', 25)->unique();
            $table->integer('id_teknisi')->unsigned();
            $table->integer('id_kulkas')->unsigned();
            $table->integer('id_tipe_pekerjaan')->unsigned();
            $table->string('temuan_masalah', 100);
            $table->date('tanggal_perbaikan');
            $table->timestamps();
            $table->foreign('id_teknisi')->references('id_teknisi')->on('teknisis');
            $table->foreign('id_kulkas')->references('id_kulkas')->on('kulkas');
            $table->foreign('id_tipe_pekerjaan')->references('id_tipe_pekerjaan')->on('tipe_pekerjaans');
        });
    }

This my 2nd table

public function up()
    {
        Schema::create('sukucadangs', function (Blueprint $table) {
            $table->increments('id_sukucadang');
            $table->string('nomor_sukucadang', 5)->unique();
            $table->string('nama_sukucadang', 35);
            $table->integer('stok');
            $table->integer('id_kategori_sukucadang')->unsigned();
            $table->timestamps();
            $table->foreign('id_kategori_sukucadang')->references('id_kategori_sukucadang')->on('kategori_sukucadangs');
        });
    }

And this is my intermediate table

public function up()
    {
        Schema::create('pemakaian_sukucadangs', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('id_perbaikan')->unsigned();
            $table->integer('id_sukucadang')->unsigned();
            $table->integer('qty');
            $table->foreign('id_perbaikan')->references('id_perbaikan')->on('perbaikans');
            $table->foreign('id_sukucadang')->references('id_sukucadang')->on('sukucadangs');
        });
    }

My Controller

class PerbaikanController extends Controller
{
    public function create()
    {
        $teknisis = Teknisi::all();
        $kulkas = Kulkas::all();
        $tipepekerjaans = TipePekerjaan::all();
        $sukucadangs = Sukucadang::all();
        return view('perbaikan.tambah', compact('teknisis', 'kulkas', 'tipepekerjaans', 'sukucadangs'));
    }


    public function store(Request $request)
    {
      
        $perbaikan = new Perbaikan;

        $perbaikan->nomor_dokumen_perbaikan = $request->nomor_dokumen_perbaikan;
        $perbaikan->id_teknisi = $request->id_teknisi;
        $perbaikan->id_kulkas = $request->id_kulkas;
        $perbaikan->id_tipe_pekerjaan = $request->id_tipe_pekerjaan;
        $perbaikan->temuan_masalah = $request->temuan_masalah;
        $perbaikan->tanggal_perbaikan = $request->tanggal_perbaikan;
        $perbaikan->qty = $request->qty;

        $perbaikan->save();

        $sukucadang = Sukucadang::findOrFail($request->id_sukucadang);
        $sukucadang->stok -= $request->qty;
        $sukucadang->update();

        $perbaikan->sukucadang()->sync($request->sukucadang, false);

    }
}

How to reduce stok in sukucadangs tables if the item is used. For example, I have item1 with stock 10, and item2 20, when I use item1 and item2 with each qty 2 and 3, then the stock of items in the sukucadangs table will automatically decrease Thank you very much



via Chebli Mohamed

Choose recipient email on Laravel email verification

I had implemented Laravel email verification (https://laravel.com/docs/5.7/verification) in my Laravel application.
By default, when a user is registered, the verification email is sent to the user. However, what i want is to send a verification email to my own email, that is, to choose the recipient, so the site administrator (in this case, me) can approve the user registration himself.
Is there any way to do this? How could it be done?



via Chebli Mohamed

How to sort through two merged collections that have different models

I have two models Cities and States. One City has 1 State and one State can have 0 or more Cities. I need to retrieve all Cities and States separately because I need to display states even if no a state has no related cities (like Alabama in the below example). The issue is I need to sort by State name first, and than by Cities in that state (if there are any)

Cities

id, state_id, name 
1, 1, San Diego 
2, 1, Hollywood
3, 2, Seattle
4, 3, Pheonix

States

id, name
1, California
2, Washington 
3, Arizona
4, Alabama 

Controller

$cities = Cities::with('state')->get(); // Returns the state relationship 
$states = States::get();

$merged = $states->merge($cities);

I would now like to sort by State name first, and than all the cities in that State and return a merged collection similar to this

{
    id: 4,
    name: Alabama,
}, 
{
    id: 3,
    name: Arizona,
}, 
{
    id: 3,
    name: Pheonix,
    state_id: 3
    state: {
        id: 3,
        name: Arizona
    }
},
{
    id: 1,
    name: California
},
{
    id: 2,
    name: Hollywood
    state_id: 1,
    state: {
        id: 1,
        name: California
    }
},
{
    id: 1,
    name: San Diego,
    state_id: 1,
    state: {
        id: 1,
        name: California
    }
}, 
{
    id: 2,
    name: Washington,

},
{
    id: 2,
    name: Seattle,
    state_id: 2,
    state: {
        id: 2,
        name: Washington
    }
}



via Chebli Mohamed

Creating a data import page for Laravel Voyager

I am using Voyager for a basic BREAD admin to a small web application I am building for a small non-profit. Yearly they need to import 300-500 new semi-complex entries into the database from Excel, so I want to build an admin script that will store all the data in the right places automatically.

Is there a structured way to add a custom controller/view to Voyager?

(I have not found such documentation yet, maybe I am blind. So I have started manually extending existing bits of Voyager, but as I get deeper I want to make sure this is the best option for future growth.)

Thank you.



via Chebli Mohamed

How to use Laravel query builder with AND where claus in PHP?

I am trying to ensure that a record exists in the database prior to performing a user related action. When I execute the query directly in my PHPMyAdmin like so (for testing purposes)

SELECT * FROM `chat_participants` WHERE `chat_id` = 2 AND `user_id` = 2

I receive the correct record. However, when I try to use Laravels query builder to achieve the same like so:

dd($this->participants
        ->where('chat_id', '=', 2)
        ->where('user_id', '=', 2)
        ->get()
        ->first());

I get null. Is there a way I can ensure that the record exists in the database using query builder? Do I need to declare AND in the query builder?

Update, I set the participants variable in my constructor:

public function __construct()
{
    $this->middleware('auth');

    $this->header = DB::table('chat_headers');
    $this->participants = DB::table('chat_participants');
    $this->messages = DB::table('chat_messages');
}



via Chebli Mohamed

Laravel Cashier multiple plans

I want to leverage the multiple plans feature of Stripe. Unfortunately Laravel Cashier still doesn't support it.
Well asking google for that topic, I noticed that I'm not the only one missing this but I wasn't able to find a package which would add this feature.
Is there some kind of best practice or a package, which I didn't find?
The alternative would obviously be to either modify Cashier by myself or implement a "new" solution without cashier.



via Chebli Mohamed

Laravel/Eloquent get all appointments from a polymorphic "member_id" through a appointment_members table

I have an appointments table and an appointment_members table and my users need to be able to get a collection of appointments by searching with a "member_id", which could be a Person, Incident or CustomerID. The appointment_members table has member_id and appointment_id columns, so the member_type (also a column) is irrelevant. This all set up by a previous dev and what is missing are the relationships on the Eloquent models. I'm just creating a simple GET route that needs to return any/all appointments by that member_id. Each row has one appointment, so if I were to pass in a member_id that returned 10 results, some could have appts and others not, but at the end of the day I just need a collection of appts that are related to that member_id. Here's a screenshot of the appointment_members table: enter image description here

If I create a simple hasOne relationship to appointments on appointment_members:

public function appointments()
{
    return $this->HasOne(Appointment::class, 'id', 'appointment_id');
}

I can get a collection of appointment_members with it's respective appointment, but not sure how I boil it down to just getting the appointments.



via Chebli Mohamed

How can I store random_bytes in a database in PHP?

Inside of my migration I have a string column named encryption_key which looks like this:

$table->string('encryption_key')->unique();

I have a Controller that uses a trait to generate the encryption commands.

public function create()
{
    $this->header->insert([
        'encryption_key' => $this->issueKey()
    ]);

    $this->participants->insert([
        'chat_id' => DB::getPdo()->lastInsertId(),
        'user_id' => Auth::id()
    ]);

    return response(['status' => true, 'chat_id' => DB::getPdo()->lastInsertId()], 200)
        ->header('Content-Type', 'application/json');
}

The trait looks like this so far

trait LiveChat
{
    protected function issueKey()
    {
        return random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
    }
}

However, upon testing this I receive this error:

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xFFX\x8Af\x1F$...' for column 'encryption_key' at row 1 (SQL: insert into chat_headers (encryption_key) values (ÿXŠf\x1F$¨ì™ÒÂø¢Ú!£”…¸ÈÍØ7ÿDå\x00Œ¿3ê))

How can I store this key to use for future reference inside my DB?



via Chebli Mohamed

Issue with Laravel 5.7 Authentication - multi auth

I am trying to implement a user registration system in Laravel 5.7 where I am facing an issue.

I have two tables for Users- Admin(created by copying default Laravel auth), new routes, new middleware for admin. Every thing works fine while using guards.

But the issue started when I wanted to limit the user login and add Approve/Disapprove functionality.

I tried to add a extra column - admin(boolean) to the Users.

In Login controller - LoginController.php Page, I added

  protected function authenticated($request, $user)
    {
        if ( $request->user()->admin != 1)
        // if($user->admin != 1)
        {
            return redirect()->route('approval');
        }
        else
        {
            return redirect('/engineer');
        }
    }

when the admin is 1 I an directed to '/enginner' where as in other case I am directed to 'approval'.

Its also working as desired!.

The real issue I am now facing is that if I try to access the 'engineer' using user whose not approved I am able to access the page. I am not sure how to restrict it. The page is still restricted to public.

Since the controller will be accessed by both the user and admin, I used __construct in the controller

web.php

Route::resource('engineer', 'engineerController');

engineerController.php

public function __construct()
        {
            $this->middleware('auth:web,admin');
        }

I am a self learner and new to laravel. I am pretty sure that I am not following the right practice. I started something and was trying to follow it till I finish. Please guide me through it.

Along with it please let me how could I have done it better.



via Chebli Mohamed

Laravel - Eager Loading

I'm trying to understand Eager Loading using Laravel to avoid generating a lot of unnecessary queries. I want to get 15 last added Posts and also get their rates from relationship of my rates table (before I was getting Posts and later in foreach I was calling for $item->avgRate() that creates 15 additional queries :S).

My Post model:

public function rates()
{
    return $this->hasMany(Rate::class);
}

public function scopeLastAdded($query, $limit = 15)
{
    return $query->latest()->limit($limit)->with('rates')->get();
}

This works, for each post, I'm also getting all rates, but the main goal is to make some function to calculate avg rate for each post and not retrieve all rates. I created a new method:

public function avgRate()
{
    return number_format($this->rates()->avg('rate'), 1, '.', '');
}

When I use with('avgRate') my model fails:

Call to a member function addEagerConstraints() on string

How can I get avgRate in some clean way with my last 15 Posts to perform only 2 queries and not 16?

Expected output:

// Post view
@foreach ($posts as $post)
   <div></div>
   <div></div> //I want to get data without performing 15 queries
@endforeach



via Chebli Mohamed

How fix error on redirect with parameters?

Having defined routes in routes/web.php as:

Route::group(['middleware' => ['auth'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
...
Route::resource('box-rooms', 'Admin\StorageSpacesController', [ 'as' => 'box-rooms', 'except' => [] ] )->middleware('WorkTextString');
Route::get( 'get-box-rooms-dt-listing', [ 'uses' => 'Admin\StorageSpacesController@get_storage_spaces_dt_listing' ] );

In control I try to redirect :

return redirect()->route('box-rooms.index', [ 'id'=>$requestData['check_in_client_id'],'action'=>'check_in' ]);
OR
return redirect()->route('admin.box-rooms.index', [ 'id'=>$requestData['check_in_client_id'],'action'=>'check_in' ]);

But in both cases I got error that route is not defined. Why eror?

laravel 5.7

Thanks in advance!



via Chebli Mohamed

How can I dynamically change the keys that Crypt uses in Laravel?

I have been researching how to use Laravel Encryption as building a homestead encryption platform is frowned upon and rightfully so.

Illuminate\Support\Facades\Crypt::encryptString('This is a secret message from user 1 to user 2');

Take the above example, this is using my APP_KEY which derives from my .env file, generation previously by php artisan key:generate. The issue is that user 1 is never issued two sets of keys to communicate only to user 2. User 3, 4 and so on could still read this message using the Illuminate\Support\Facades\Crypt::decryptString method.

Currently, my database is set up to have a chat header. This contains information about what is communicating. All participants will use these keys for encryption and decryption - thus any outside users not being able to decrypt the messages.

public function up()
{
    Schema::create('chat_headers', function(Blueprint $table) {
        $table->increments('id');

        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

        $table->string('private_key')->unique();
        $table->string('public_key')->unique();
    });
}

I also have a chat participants, this contains information about who is communicating:

public function up()
{
    Schema::create('chat_participants', function(Blueprint $table) {
        $table->increments('id');

        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

        $table->integer('user_id')->unsigned();

        # TODO: Build RBAC

        $table->index(['user_id']);
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Finally, I have a table for message logs. This contains the encrypted message followed by what chat room they're associating with.

public function up()
{
    Schema::create('chat_messages', function(Blueprint $table) {
        $table->increments('id');

        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

        $table->integer('chat_id')->unsigned();
        $table->string('message');

        $table->index(['chat_id']);
        $table->foreign('chat_id')->references('id')->on('chat_headers')->onDelete('cascade');
    });
}

How can I dynamically assign new keys to the Illuminate\Support\Facades\Crypt to use in order to encrypt messages between a chat party?



via Chebli Mohamed