jeudi 28 février 2019

How to leave the data in database if edit form field is left empty

I getting many inputs from a user in create form(>50 fields) where I would like to edit those details in edit form.

I have made all the fields nullable so that while editing, the fields are left alone,

Controller:

public function update(Request $request, $id)
    {
        $engineers = Engineers::findOrFail($id);
        $engineers->input1 = $request->input('input1');
        $engineers->input2 = $request->input('input2');
        $engineers->input3 = $request->input('input3');
        $engineers->input4 = $request->input('input4');
        $engineers->save();
    }

When I try to edit input2 leaving everything blank, all the other fields are blank in the database.

Another option I found out was

public function update(Request $request, $id)
{
    $engineers = Engineers::findOrFail($id);
    if($request->input('input1')){
        $engineers->input1 = $request->input('input1');
    }
    if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    } 
    if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    }
     if($request->input('input2')){
        $engineers->input2 = $request->input('input2');
    }

    $engineers->save();
}

By doing the above, The corresponding record changes and all the other fields are left intact.

I also noticed that empty edit form can be submitted.

Are there any other better approach to this?



via Chebli Mohamed

vue component not compiling on laravel app

I have a laravel app not compiling new created vue i have created Abc/abc.vue file and abc-components.js file followed every thing as guided.

npm run watch

command not showing this component all other components compiling properly.

abc.vue

<template>
<h1>ap navbar component</h1>
<h3></h3>
</template>
<script>
export default {
    data() {
        return {
            message: 'test message'
        }
    },
    mounted() {
        console.log("apnavbarcomponent mounted");
    }
}
</script>

abc-components.js

window.Vue = require('vue');
Vue.component('hbabc', require('./components/abc/abc.vue').default);

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



via Chebli Mohamed

Upload an image and file to forum

I have searched for the SO and didn't find any article or post related to this. How do I upload an Image using the Image Intervention and upload a normal file with in a single forum without opening a new page for the uploads.

Hope the below Answer would help someone out there.



via Chebli Mohamed

I want to upload .heic file in php

I want to upload heic image in my project. My project is developing using laravel. All other images such as JPG and PNG. Is it possible? If it is possible what should I have to do?



via Chebli Mohamed

Eloquent: Paginate Two Query Result With Different Condition (Has different with())

Hello fellow Laravel programmer.


I'm on Laravel 5.7 and I'm having 4 tables:

outlets - belongsTo merchants, also belongsToMany promos

promos - belongsTo merchants, also belongsToMany outlets

merchants - list of merchants that has many promos (hasMany promos, hasMany outlets)

outlet_promo - that connects outlets and promos, only store their IDs


Condition 1#:

Every merchant's promo that only active in specific outlet has outlet_promo values, such as

outlet_promo
outlet_id      promo_id
    1             1

Means that the promo_id 1 only active on outlet_id 1.

Condition 2#:

Now if a promo active on all merchant's outlets means that no relation on outlet_promo. (I'm avoiding too many storing in outlet_promo table)

Fetching Data

I'm trying to get all outlets where has active promos that can be active in some outlets only and active in all outlets, resulting me in this two query:

  1. Getting all outlets where has active promos and its promo available in every outlets
$outlets_all = Outlet::with(['merchant.promos' => function ($q) {
            $q->doesntHave('outlets');
        }])->whereHas('merchant.promos', function ($q) {
            $q->whereDate('start_date', '<=',  date('Y-m-d'));
        })->doesntHave('promos.outlets');

  1. Getting all outlets where has active promos and its promo only active in selected outlets
$outlets_selected = Outlet::with(['merchant.promos' => function ($q) {
            $q->has('outlets');
        }])->whereHas('promos', function ($q) {
            $q->whereDate('start_date', '<=',  date('Y-m-d'));
        });

The key difference is in with condition

Goals

Within these two queries I managed to get the desired output. But now the goal is I want to paginate both result in one object so I can lazy load the outlets on the view using AJAX. I want to display list of outlets that has promos (all outlets or selected outlets) with list of active promos that outlet has.

What I have tried so far

I tried to union() and unionAll() both queries, resulting correct outlets, but has wrong promos list from merchant.promos. It seems that the union operation messes up the promos. Every merchant's promos seems have same value, when actually they should be different.

I even tried to merge the query with two with() operation like this:

$merge = Outlet::with(['merchant.promos' => function ($q) {
            $q->has('outlets');
        }], ['merchant.promos' => function ($q) {
            $q->doesntHave('outlets');
        }])->whereHas('promos', function ($q) {
            $q->whereDate('start_date', '<=',  date('Y-m-d'));
        })->orWhereHas('merchant.promos', function ($q) {
            $q->whereDate('start_date', '<=',  date('Y-m-d'));
        })->doesntHave('promos.outlets');

And it just results the same as the union I did before.

I'll be tremendously grateful for any help. Thank you.



via Chebli Mohamed

How many Digits i can stored using money, double, float types in PostGres?

i don't know much more aboout postgres, i just want to know that suppose using int we can store 8 digits then same using money types or float types how many digits we can store ??

i have search on internet too and find this : https://www.postgresql.org/docs/9.5/datatype-money.html

And what is range ?? like -92233720368547758.08 to +92233720368547758.07



via Chebli Mohamed

Eloquent Get Models based on fields in related tables

I have multiple Models related to my User model(eg: profiles, addresses, orders,...etc)

I want to get all the users that were updated in the past 24 hours, based on the update_at field in each of the related tables accordingly.

I have found the following if u have one related table, but in my case I have more than 3 tables that I need to check:

$users = User::with('orders')
            ->where('updated_at', $valueA)
            ->whereHas('orders', function($query)
                {
                    $query->where('updated_at', $valueB);
                })->get();

I hope someone can help me to know how to apply this for multiple where clauses n=on multiple related tables.



via Chebli Mohamed

Laravel Ajax Request $request empty result

I have an ajax request method post like this on the view :

$.ajax({
                data: { test : 1337, _token: "" },
                type: "POST",
                url: '',
                success: function (res) {
                    console.log(res)
                },
            });

and here is my route code :

Route::post('backend/blog/get_image_by_parent_id', 'Backend\BlogController@get_image_by_parent_id')->name('get_image_by_parent_id');

here is my controller :

public function get_image_by_parent_id(Request $request)
    {
        echo json_encode($request);
    }

when i look in network tab it's show me like this :

Network tab debug result

Anyone can help me out ?



via Chebli Mohamed

Laravel Implicit model binding naming convention?

I am using implicit model binding on my controller actions, but I have have a model called VerifiedDocument and no matter what I put in as the model name I cannot seem to get it to load into my action, but if I do:

    Route::bind('verificationDocument', function ($value) {
        return VerificationDocument::where('id', $value)->first() ?? abort(404);
    });

it works.

What naming convention does Laravel use for implicit model binding?



via Chebli Mohamed

Laravel limiting scope of models automatically based on API user

I have an API that uses bearer tokens for authentication. Bearer tokens are stored against users. There is some middleware that checks if there is a valid bearer token in the request, and 401's if not.

Given I can infer the user from the token, I'm wanting to limit the scope of all model lookups in this API controller to only show results from the users company id.

Does Laravel have some neat magic way of doing this? Or am I going to be looking up the user again in the controller constructor and adding where clauses into every single action?


Basically I'm wanting to avoid having to do this:

public function __construct()
{
    # 401 if there isn't a valid bearer token in the request
    $this->middleware('apitokencheck');

    # Boo to this
    $user = UsersModel::where("api_token", $request->api_token)->first();
    $this->companyContext = CompaniesModel::find($user->company_id);
}

...

public function get(Request $request)
{
    # Boo to this also
    $where = [ 
        "company_id" => $this->companyContext->id
    ];

    # Filters
    return InspectionsModel::where($where)->get();
}



via Chebli Mohamed

Laravel collection issue

after a lot googeling and searching through stackoverflow i decided i need your help.

I have to get the quantity of supplies for each supply by a certain supplier. I know that sounds weird but let me explain:

I have a Supplier model wich has many supplies and each supply has many stocks wich have a quantity. So now im building a view in wich i want to represent each Supply with their quantity on a certain supplier.

So thats what I came up with in my controller:

foreach ($suppliers as $supplier) {

        foreach($supplier->supplies as $supply){

            if(!$comp_supplies->contains('name', $supply->name)){

                $comp_supplies->push(['name'=>$supply->name, 'supplier'=>[['name'=> $supplier->name, 'quantity' => $supply->stocks->first()->quantity]]]);

            }elseif($comp_supplies->contains('name', $supply->name)){

                $array = (['name'=> $supplier->name, 'quantity' => $supply->stocks->first()->quantity]);
                $array2 = $comp_supplies->where('name', $supply->name)->first()['supplier'];

                array_push($array2, $array);

                //dd($array2);
                $comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2;
                dd($comp_supplies->where('name', $supply->name)->first()['supplier']);
            }
        }

    }

So im iterating over my suppliers and iterate again over the supplies from each of them. Now I want to fill the collection I want as a result.

If this collection not contains a supply with the name of "$supply->name", I push an array with the supply-name and create an array "suppliers" in which I also set the first entry with the current supplier information.

Now we are getting close to my problem.

If comp_supply already contains a supply with the current supply-name, if have to push the new supplier into the already existing "supplier" array we created in the first "if".

Therefore I created $array, which holds the new supplier-informations, and $array2, which holds the supplier-array ($comp_supplies->where('name', $supply->name)->first()['supplier']) we already made.

Now, if i push $array onto $array2 and dd(array2) everything works as i want it to. But if I now set

$comp_supplies->where('name', $supply->name)->first()['supplier'] = $array2 

and then

dd($comp_supplies->where('name', $supply->name)->first()['supplier']);

it didnt change.

Im stuck on this Problem for nearly 2h and getting really frustrated.

Please if anyone has an idea what I could do to solve this, or knows where i can look next, let me know.

Here are also the migrations:

Supplier:

public function up()
{
    Schema::create('suppliers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->unsignedInteger('coordinates_id')->index()->nullable();
        $table->timestamps();
    });
}

Supplies:

public function up()
{
    Schema::create('supplies', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->unsignedInteger('supplier_id');
        $table->foreign('supplier_id')
              ->references('id')
              ->on('suppliers')
              ->onDelete('cascade');
        $table->timestamps();
    });
}

Stocks:

    public function up()
{
    Schema::create('stocks', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('supplies_id');
        $table->foreign('supplies_id')
              ->references('id')
              ->on('supplies')
              ->onDelete('cascade');
        $table->integer('quantity');
        $table->timestamps();
    });
}



via Chebli Mohamed

Unhandled error event: Error: connect ECONNREFUSED

I'm using pm2 to ensure laravel-echo-server is running. Performing a pm2 logs 0 gives me some errors. I'm running the server on a Google Compute Engine Instance and have setup some firewall ingress rules.

firewall rules

0|echo-ser | ⚠ Starting server in DEV mode... 
0|echo-ser | 
0|echo-ser | ✔ Running at localhost on port 6001 
0|echo-ser | ✔ Channels are ready. 
0|echo-ser | ✔ Listening for http events... 
0|echo-ser | 
0|echo-ser | L A R A V E L E C H O S E R V E R 
0|echo-ser | 
0|echo-ser | version 1.5.0 
0|echo-ser | 
0|echo-ser | ⚠ Starting server in DEV mode... 
0|echo-ser | 
0|echo-ser | ✔ Running at localhost on port 6001 
0|echo-ser | ✔ Channels are ready. 
0|echo-ser | ✔ Listening for http events...

/root/.pm2/logs/echo-server-error.log last 15 lines: 
0|echo-ser | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14) 
0|echo-ser | [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379 



via Chebli Mohamed

Lumen API select data with group by aggreated

I'm currently using Lumen 5.7 for my back end API .I need to select some fields from multiple tables with using left join. I have the following query(Plain mysql query)

SELECT issue_id,issue_receipt_id, date_format(issue_datetime, '%d-%m-%Y') as issue_datetime,
issue_item,sum(issue_wt) as issue_wt, round(avg(issue_pure),3) as issue_pure,
sum(issue_fine) as issue_fine, sum(issue_cash) as issue_cash,
sum(receipt_wt) as receipt_wt, sum(receipt_fine) as receipt_fine,
pure_name as issue_item_name 
FROM item_issues 
LEFT JOIN receipt_items ON receipt_id = issue_receipt_id 
LEFT JOIN purities ON pure_id = issue_item
group by issue_receipt_id;

And I have tried in lumen as like,

$receipts = DB::table('item_issues')            
            ->leftJoin('receipt_items', 'receipt_items.receipt_id', '=', 'item_issues.issue_receipt_id')
            ->leftJoin('purities', 'purities.pure_id', '=', 'item_issues.issue_item')
            ->select('issue_id', 'issue_receipt_id', DB::raw("date_format(issue_datetime, '%d-%m-%Y') as issue_datetime"), 'issue_item', 'pure_name', DB::raw('sum(issue_wt) as issue_wt'), 
            DB::raw('round(avg(issue_pure),3) as issue_pure'),
            DB::raw('sum(issue_fine) as issue_fine'),
            DB::raw('sum(issue_cash) as issue_cash'),
            DB::raw('sum(receipt_wt) as receipt_wt'),
            DB::raw('sum(receipt_fine) as receipt_fine'))
            ->groupBy('item_issues.issue_receipt_id', 'item_issues.issue_item')->get();

But it producing error like Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'item_issues.issue_id' which is not functionally dependent on columns in GROUP BY clause; But I have to select the above fields, how to do this without the issue. And I have tried to disable strict mode but I don't know where to disable this option whether in .env or in some other file. I couldn't find the database.config in lumen. Any one can help on this.



via Chebli Mohamed

define all my Enumerations in one file Laravel 5.7

i want to create a file to define all my Enumerations and later to use them in model or migrations because i have the same enumeration in many models and i don't want to refined them each time
suggestions ??



via Chebli Mohamed

Laravel print last executed sql query with Query log

DB::enableQueryLog();
$mines = Cranks::where([['crank_id', '=', $this->crank_id], ['mine_id', 'like', '%'.$script_value->mine_id.'%'] ])->get();
$querylog =  DB::getQueryLog();
dd($querylog);

exit;

This code prints the querylog with bind array and all - How can I get the pure sql, so I can run it in PhpMyAdmin



via Chebli Mohamed

Retrieve fillable fields in Laravel

In laravel 5.4, I'm able to retrieve fillable fields by using fillable index of model instance.

$model = new AnyClass();
dd($model['fillable']);

The above code prints all fillable fields of AnyClass. But the same code prints null on laravel 5.6. I know I can retrieve fillable fields using $model->getFillable(). My question is what is the reason / why it is not working in laravel 5.6 but works in 5.4?



via Chebli Mohamed

Laravel payment integration page goes blank

Code below

public function PayCCAvenue(Request $request)
        {
            $parameters = [

                'tid' => '1233221223322',
                'order_id' => '1232212',
                'amount' => '1200.00',
                'firstname'=>'test',
                'email'=>'email@fffm.com',
                'phone'=>'7736190194',
                'productinfo'=>'sfszgvfsg'

            ];



            // gateway = CCAvenue 

            $order = Payment::gateway('CCAvenue')->prepare($parameters);
           //dd(Payment::process($order));
            return Payment::process($order);

        }

After return Payment::process($order); page goes blank. dd(Payment::process($order)); giving result. tried different laravel packages. same issue



via Chebli Mohamed

How to do in Laravel, subquery where

I've see a lot of examples on how to do subquery with whereIn, but i need to do the same with where, like this:

select *
  from products
 where (select count(*) 
             from items 
           where items.product_id = products.id 
              and items.exported = 0) = 0;

I simply tried this code:

Product::where(function($q) {
    $q->selectRaw('count(*)')
        ->from('items')
        ->whereRaw('items.product_id', 'products.id')
        ->where('items.exported', 0);
}, '=', 0);

In this solution the result query is something like this:

select *
  from products
where (items.product_id and exported = 0);

The builder loose the subquery for some reason. How i can solve ?



via Chebli Mohamed

Print selected backend rows to Dynamic PDF

I've built a backend list in OctoberCMS and I have a button to create a PDF with alle the rows of this list. Each row produces one PDF page. But now I want to print only the selected rows? Does anyone know how to do this?

This is my code at the moment:

   public function export()
{
    $lists = $this->makeLists();
    $widget = reset($lists);

    /* Add headers */
    $headers = [];
    $columns = $widget->getVisibleColumns();
    foreach ($columns as $column) {
        $headers[] = \Lang::get($column->label);
    }

    /* Add records */
    $getter = $this->getConfig('export[useList][raw]', false)
        ? 'getColumnValueRaw'
        : 'getColumnValue';

    $model = $widget->prepareModel();
    $results = $model->get();
    $records = [];
    foreach ($results as $result) {
        $record = [];
        foreach ($columns as $column) {
            $value = $widget->$getter($result, $column);
            if (is_array($value)) {
                $value = implode('|', $value);
            }
            $record[] = $value;
        }
        $records[] = $record;
    }
    return \Renatio\DynamicPDF\Classes\PDF::loadTemplate('export-data-pdf',
        ['headers' => $headers, 'records' => $records])->stream('export.pdf');
}



via Chebli Mohamed

return response()->download(storage_path('app/files/gggusers.xlsx')); show's blank page

I have this code

return response()->download(storage_path('app/files/gggusers.xlsx'));

in my controller. It executes without any problem but instead of triggering the browser to download the excel file, it just displays a blank white page. I'm positive the file name & location is correct, because if I just change the file name gggusers.xlsx to something else or I delete the file, Laravel will display this error

The file "D:\web\speak\storage\app/files/gggusers.xlsx" does not exist.



via Chebli Mohamed

Trying to get property '' of non-object (View:

I am trying to fetch a user based on their corresponding District/ area by the ID stored in the user table,

I am able to fetch the result for District where as for the Area, I am getting error,

Trying to get property 'area_name' of non-object (View: user-index.blade.php)

User 

id | district_id | area_id | user_name

District

id | district_name

area

id | district_id | area_name

Controller

 $users = Users::simplePaginate(5);

        return view('user-index',compact('users'));

Model

User

public function districts(){
        return $this->belongsTo('App\Districts','district_id','id');
    }

    public function areas(){
        return $this->belongsTo('App\Area','area_id','id');
    }

blade

 @foreach ($users as $user)
                                -  I get result
                               - I get result
                               -- I get error 

@endforeach



via Chebli Mohamed

laravel Asset() function break down after deployment

i had developed a laravel web app, which works fine and great on local machine after going online on a shared hosting server i have some issues displaying the logo and the website images using the asset() helper function, however the css and js are accessible and works fine (also using the asset function) i deployed the App following the steps bellow: 1- i created a directory called repositories outside the public_html (the root document of mydomain.com) and i copied inside it directory soukelafalah (contining all the files of my laravel project) 2- i moved the laravel public directory files into the public_html directory 3- i edited the index.php in public_html as follow :

require __DIR__.'./../repositories/SoukElfalah/vendor/autoload.php';

 $app = require_once__DIR__.'/../repositories/SoukElfalah/bootstrap/app.php';

4- i run php artisan storage:link and the link is succufully created 5- i had run also ln -s /home/dtruxpgw/repositories/SoukElfalah/storage/app/public /home/dtruxpgw/public_html/storage 6-the route and the css is working fine but the logo and the images are not displayed and shows a 404 error as shown in the image below
So please can any one point what i am missing? and when i put asset('/storage/images/thumbs/'.$img_name)}}" am i pointing to the storage directory in the public_html or in the one in the public folder of my laravel app directory Thank you in advance . enter image description here



via Chebli Mohamed

Show data with certain condition only in blade

I have a problem where I don't know how to show the subject where the sum '>0', I managed to show all of the subjects, but it shows with the subject that has sum '0' too. I'm not sure where to put the condition code, is it in view or controller.

this is my controller

    public function showSubjectListFinalYear(){

        $t1  = DB::table('matrices')->where('total_subject_left','<',10)->sum('teknologi_dan_sistem_maklumat');
        $t2  = DB::table('matrices')->where('total_subject_left','<',10)->sum('struktur_diskrit');
        $t3  = DB::table('matrices')->where('total_subject_left','<',10)->sum('teknik_pengaturcaraan_1');
        $t4  = DB::table('matrices')->where('total_subject_left','<',10)->sum('logik_digital');
return view('admin.final_year_subject_list')>with(compact('t1','t2','t3','t4'));

this is the code in my view

   <thead>
                        <tr>
                            <th>Subject name</th>
                            <th>No. of students</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="gradeX">
                            <td>Teknologi dan Sistem Maklumat</td>
                            <td style="text-align:center"></td>
                        </tr>
                        <tr class="gradeX">
                            <td>Struktur diskrit</td>
                            <td style="text-align:center"></td>
                        </tr>
                        <tr class="gradeX">
                            <td>Teknik Pengaturcaraan 1</td>
                            <td style="text-align:center"></td>
                        </tr>
                        <tr class="gradeX">
                            <td>Logik Digital</td>
                            <td style="text-align:center"></td>
                        </tr>



via Chebli Mohamed

Ajax remove link on Dropzone Laravel POST data empty result

I created multiple upload with Dropzone, and added remove link with ajax request but when I did echo json_encode($_POST); here the POST data result was empty. Anyone have any solution ?

here is my following code :

var token = $('[name=_token').val();
    Dropzone.autoDiscover = false;
    var imageUpload= new Dropzone(".dropzone",{
        url: "",
        maxFilesize: 2,
        method:"post",
        acceptedFiles:"image/*",
        paramName:"image",
        dictInvalidFileType:"Type file ini tidak dizinkan",
        addRemoveLinks:true,
        headers : {
            'X-CSRF-Token' : token
        }
    });

    //Event ketika Memulai mengupload
    imageUpload.on("sending",function(file, xhr, formData){
        var token_upload = 1337;
        formData.append("token_upload" , token_upload);
    });

    imageUpload.on("removedfile",function(formData){
        $.ajax({
            data    : { "token_upload":1337 },
            type    : "POST",
            url     : "",
            cache   : false,
            processData: false,
            contentType: false,
            dataType: 'json',
            beforeSend: function (request) {
                return request.setRequestHeader('X-CSRF-Token', "");
            },
            success: function(data)
            {
                console.log("Foto terhapus");
            },
            error: function()
            {
                console.log("Error");
            }
        });
    });



via Chebli Mohamed

required array fields with another array fields in Laravel

I am validating two arrays in Laravel frame work. I would like to validate the relation between this two array fields. How can I validate this in request?

'rank.*' => 'integer|min:1|required_with:score.*',
'score.*' => 'numeric|required_with:rank.*',



via Chebli Mohamed

How to modify http_host in laravel 5

How to modify the return of request()->getHttpHost() in Laravel 5.

I used a middelware to modify $_SERVER[HTTP_HOST], but it was not affected.

class ModifyHttpHost
{
    public function handle($request, Closure $next)
    {
        $_SERVER['HTTP_HOST'] = 'another.com';
        return $next($request);
    }
}



via Chebli Mohamed

mercredi 27 février 2019

Get base url in blade laravel 5.7

I want to display metaimage when i share my link. But i am unable to get image. here is my code. please suggest me what is in my code. Iam new laravel.

<meta property="og:image" content="../storage/uploads/">



via Chebli Mohamed

Laravel 5.7: From where the password-exposed-cache comes from?

I've found out this directory by accident in a project.

The path is:

storage/app/password-exposed-cache

enter image description here

Just by looking at the directory content (sub dir named 9b) and the file within, I can guess it's been created by a Laravel itself or a package. Not by a human.

When I open the c34.cache (weights 11 KB) I just see some binary data.

enter image description here

What is this? Where does it come from? What it contains? Can I delete it?

Brief internet research was unsuccessful.



via Chebli Mohamed

Unknown column 'imageable_type' in 'field list' when insert one-to-one polymorphic relation laravel 5

My Image migration

class CreateImagesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('url');
        $table->integer('imageable_id');
        $table->string(' imageable_type');
        $table->timestamps();
    });
}

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

My Image model

class Image extends Model
{
/**
 * Get the store of the image
 */
public function store()
{
    return $this->morphTo('App\Store', 'imageable');
}

/**
 * Get the item of the image
 */
public function item()
{
    return $this->morphTo('App\Item', 'imageable');
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'url', 'imageable_id', 'imageable_type'
];
}

My Store model

class Store extends Model
{
/**
 * Get the user that owns the store.
 */
public function user()
{
    return $this->belongsTo('App\User');
}

/**
 * Get the items of a store
 */
public function items()
{
    return $this->hasMany('App\Item');
}

/**
 * Get the store's image.
 */
public function image()
{
    return $this->morphOne('App\Image', 'imageable');
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'address', 'description','user_id',
];
}

So I have Store,Item,Image models and a store/an item can own only one image.

And I am trying to save a store and an image belongs to that store in the 'store' action of the StoreController:

public function store(Request $request){
    $request->validate(....);

    $store = $user->stores()->create($request->all());

    // Upload the image to s3 and retrieve the url
    ...
    $url = Storage::disk('s3')->put($path, $image);
    Storage::cloud()->url($path);

    // Trying to save the image to databse
    $image = new Image(['url' => $url]);
    $store->image()->save($image); // => Error

}

I am following the example here but it does not work

Any pointers will be appreciated.



via Chebli Mohamed

"failed to open stream: Permission denied" after 777 my entire app

I'm growing several grey hairs trying to work this one out.

All of a sudden in my Laravel project, I can't upload any files to my symlinked public/storage directly as it's complaining about permissions.

I then 777'ed every single file in the app (I know, I know), and it's still complaining about permissions. I've also run composer dump-autoload, which never seems to do anything but I thought I'd give it a go anyway.

Does anyone know what else I can try? I can verify everything is 777, so I can't see why any permissions would fail...



via Chebli Mohamed

Laravel 5 bilingual Product model

I am looking for the most straightaway solution and breaking my head about implementing a bilingual Product model with only one basic requirements: the product query should only deliver results where the product name in the app()->locale language is set.

I'm stuck right at the beginning to decide wether I should keep completely different models (Product_en and Product_es), this would make querying easiest I guess, or have just one Product model with the English texts, with hasOne() methods pointing to the Spanish translations? In the latter case, how would I effectively query for entries which have translations?

Thanks a lot for any hints. Cheers.



via Chebli Mohamed

Update/Delete user account in laravel

i wana to know how i can let each user can access his/her profile and update user name, email, password, ets.., and have another option to delete his/her account in Laravel 5.7, and thank you.



via Chebli Mohamed

Mail not being queued

Within Laravel 5.7, I have run this using database queue and everything worked fine. When using Redis, on the other hand, I am having an issue with public $queue. For some odd reason:

  1. If I set public $queue the email is sent straight away.
  2. If I remove public $queue mail is added to the default queue.

I have a file similar to below:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class TestEmail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $queue = 'mail';
}

The mail class is called using send() similar to: Mail::to($request->user())->send(new OrderShipped($order));

When I switch to defining queue then everything works as should:

Mail::to($request->user())
    ->queue(new OrderShipped($order));



via Chebli Mohamed

laravel paypalintegration with no login

I have implement an integration for paypal in laravel but when i go to pay he shows that screen

enter image description here

and same exemple show this screen

enter image description here

how i Can make it like this 2. thanks



via Chebli Mohamed

Get data from database with condition and show it in a view

This is the data that I have in database

This is what I want to make in the view.blade.php

What I want to do is I want to get the data from the database, if the data inside the column is 1, I want to get the column name as you can see in image 2, but there could be more than 1 column name because the column with data can be column A,B,C... etc.. and I want to show the student name and the subject (a,b,c... etc) if the data in it is '1' in the view. I stuck on how to get all those subject A,B,C.. this is the code that I have written, but it is incomplete because I don't know what to add on it to make it as what I have mentioned above. Hopefully, someone can help me. Thanks in advance

if($row->'A'=='1'){i dont know what should i put here so that i cant get the column name 'A' and print it in view.blade.php}



via Chebli Mohamed

With laravel blade input id = ex. id="group-" howto name old('xxxxx')

With laravel blade if input id = ex. id="group-"

howto name old('xxxxx') ?



via Chebli Mohamed

Where between created_at column?

I've been struggling with date range between (single column ) created_at column, so far i tried this

$startDate = date('Y-m-d', strtotime($request->start_date));
$endDate = date('Y-m-d', strtotime($request->end_date));
....->whereBetween('created_at', [$startDate,$endDate])

created_at format is by default ( Y-m-d H:i:s ), in post data i'm getting this format ( Y-m-d )

I know it's wrong query,but how should i think ?

Do i've to use ->whereRaw() ? or something with ->whereDate ?

Please help



via Chebli Mohamed

How to configure local issuer certificate in Wamp using OpenSSL in Laravel project?

Am trying to send SMS Locally with Nexmo but i configured my Wamp server to use OpenSSL but when i try sending, i get this error.

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Am sending the message in a route from my web.php like this,

Route::get( '/sms/send/{to}', function(\ Nexmo\Client $nexmo, $to){
     $message = $nexmo->message()->send([
        'to' => $to,
        'from' => env('NEXMO_NUMBER'),
        'text' => 'Sending SMS from Laravel. Woohoo!'
    ]);
    Log::info('sent message: ' . $message['message-id']);
});

Need help of how i can fix this.



via Chebli Mohamed

Laravel shell_exec command js-beautify not run working

I'm trying to run

echo shell_exec(' echo 3');
echo shell_exec('cat m.html | js-beautify  --type html -o m.html ; echo 43');
echo shell_exec(' echo 53');

I got as an output

3 53

and m.html is not beautified also when I run the same command through command line the file is beautified.



via Chebli Mohamed

Laravel debugger - enable/disable depending on IP address while caching implemented

We need to eneble/disable Laravel debugbar depending on IP address. It works if we clear/disable the caching.

But it does not work when caching enabled. here is my code

//Enabling DEBUGBAR in Production Only for developers
if(in_array($request->ip(), [ip addresses])) {
    config(['app.debug' => true]);
}

We are using configuration and route caching. What would be the best way to achieve this?

Laravel version - 5.4

Debugbar version - 2.2



via Chebli Mohamed

How to query a model and its related model in laravel

I am building a Laravel 5.5 project where i have 2 related models, User and Service with a relationship like so: Inside User.php

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

and inside Service.php

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

I need to query the service model for a service column where the query is either service_name or the name of a user. In effect, the query will search for the item in the service model and the related user model. I have written the query below but its returning an empty collection:

$items = Service::where('service_name', 'LIKE', "%".$query."%")
                 ->whereHas('user', function($q) use ($query){
                  $q->where('name', 'LIKE', "%".$query."%");))->get();

What am i doing wrong?

NB: My search on google, stackoverflow and laravel documentation didn't give exactly what i need hence my question please.



via Chebli Mohamed

Moving Laravel project to new PC

So I have moved my project from my pc to my laptop and a lot of lines do not work such as Auth, Form, @Extends, @Section.

I have tried

Composer Install
Composer Update
composer dumpautoload

Nothing worked for me



via Chebli Mohamed

Ping to Laravel Homestead is Fine but Web Connection Refused

I just set up a homestead on my Windows 10 machine. Everything looks fine but page is not loading. I am getting connection refused on my browser.

I have asked this on Laracasts with details

https://laracasts.com/discuss/channels/servers/ping-to-homestead-is-fine-but-connection-refused#reply=495171

I think it is a minor issue but don't know where and what to look for.



via Chebli Mohamed

Too few arguments Laravel

I'm currently in the middle of working on an old project of mine, nothing has changed although all of a sudden I'm seeing weird error debug page after logging in with the following:

Too few arguments to function 
Illuminate\Auth\Events\Attempting::__construct(), 
2 passed in /*/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php on line 583 and exactly 3 expected

The last Application Frame comes from the following:

public function handle($request, Closure $next, $guard = null)
{
    if (auth()->guard($guard)->check()) {
        return redirect()->route(home_route());
    }

    return $next($request);
}

Does anyone have any ideas? it's Laravel 5.6



via Chebli Mohamed

Laravel-5.6 'LIKE ' in where and or where select

I use this query and i get a error :

$description = $request->get('description');
                $description_query = Transcationhistorique::where(function ($query) use ($description, $user_id) {
                    $query->where('receiver_id', $user_id,'description', 'LIKE','%' . $description . '%')
                        ->orWhere('description', 'LIKE','%' . $description . '%','sender_id', $user_id);
                })->get();

and this is the error that I get :

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from transcation_historique where (sender_id = 32 and 0 = %salaire% and 1 = LIKE and 2 = description) or receiver_id = 32)"

and this what really i want to run:

select * from `transcation_historique` where (`sender_id` = 32 and `description` = %salaire%) or (`receiver_id` = 32 and `description` = %salaire%)



via Chebli Mohamed

How to check if table is already joined in Laravel Query Builder

I created a query. I want to join my table with students table:

$query->leftJoin('students', 'learners.student_id', '=', 'students.id');

But I don't know my table joined before or not. How should I do that?



via Chebli Mohamed

Laravel Method does not exist after rename

I have a little problem here, after i renamed a method from store to save also i was renamed in the Route

Route::post('blog', 'Backend\BlogController@store');

to

Route::post('blog', 'Backend\BlogController@save');

but when i hit submit it's still show me Method [store] does not exist.

anyone can help me out ?

Thank you



via Chebli Mohamed

how to show reminder notification in laravel5

i have a reminder table. how i can show reminder at a specified time.

This is my table

id | due_date | due_time |     notes     | created_by
------------------------------------------------------
 1 |2019-02-27| 10:00:00 | Hai, testing  |  Rahul

I wand show the content from this table at specified time (due_time)



via Chebli Mohamed

mardi 26 février 2019

Get row count to Laravel blade View

I'm trying to get count of total users registered on the system to my dashboard. Can I get users row count of users table Laravel View Directly ?



via Chebli Mohamed

Laravel. BroadcastServiceProvider throw an error

Hi guys I have a problem using BroadcastServiceProvider. when I'm trying to fire an event I get this error message Target [Illuminate\Contracts\Broadcasting\Factory] is not instantiable. if I do composer install dump etc. it says the same error.



via Chebli Mohamed

how to convert webp image to jpeg or png by using intervention image laravel

I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket.



via Chebli Mohamed

how to use third party service credentials from database in laravel 5.4?

Suppose I am using multiple Email services (e.g Mailgun, Mailchimp etc), now I want to store the credentials of each email service in the database instead of config/service.php. So that I can call/use different email services for sending email in a different situation.



via Chebli Mohamed

How to Show files in browser instead of download using laravel 5.6?

I want to show files (pdf, docx etc) in browser once click on a button instead of download.



via Chebli Mohamed

Stay on same component of page after refresh browser in ReactJS

I am very new to ReactJS. My query is I want to stay on same component of page in ReactJS. Below is my code.

App.js

import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom'

import { authenticationService } from './_service/authentication.service'


import { PrivateRoute } from './components/Routes/PrivateRoute'; 
import Navbar from './components/Navbar/Navbar' 
import Landing from './components/Landing/Landing'
import Login from './components/Login/Login' 
import Register from './components/Register/Register' 
import Home from './components/Home/Home'
import SideBar from './components/SideBar/SideBar';

class App extends Component {   render(){
    return (      
      <Router>
        <div className="App">
          <Navbar />             
          {authenticationService.currentUserValue ? <SideBar/> : null}                                    
          <Route exact path="/" component={Landing} />
          <div className="container">
            <Route exact path="/register" component={Register} />
            <Route exact path="/login" component={Login} />                        
            <PrivateRoute exact path="/home" component={Home} />
          </div>
        </div>
      </Router>      
    )   } }

Above route is main route file of my project after login it redirects me to home page. On Home page i am loading Header, Sidebar and Content(Component). Here the content(Component) is different which depends on sidebar links.

Home.js

import React, { Component } from 'react'
import { BrowserRouter as Router} from 'react-router-dom'

// import Home from './components/Home/Home'
import { authenticationService } from '../../_service/authentication.service'
// import Navbar from '../Navbar/Navbar'
import Sidebar from '../SideBar/SideBar'
// import Landing from '../Landing/Landing'
import Profile from '../Profile/Profile'
import AboutUs from '../Profile/AboutUs'

class Home extends Component {
    constructor(props){
        super(props);        

        if (authenticationService.currentUserValue) { 
            // this.props.history.push('/home');
            this.props.history.push('/home');//this.state.initialPage
        }
        this.state={
            initialPage:<Profile/>
        }
    }

    routeSidebar = (flag) => {

        switch(flag) {
            case 'AboutUs':
                this.setState({
                    initialPage:<AboutUs/>
                })
                break;
            default:
                this.setState({
                    initialPage:<Profile/>
                })
                break;
        }        
    }
    render() {  
        const {initialPage} = this.state; 
        return (
                <Router>
                    <div className="Home">
                    <Sidebar routeSidebar={this.routeSidebar} />
                    {initialPage}
                    </div>                
                </Router>   
        );
    }
  }

  export default Home;



via Chebli Mohamed

Get user ID via Auth::user Laravel

I want to call the ID of the user where the button will only display if the Auth::user verifies the login user with the ID of 1066. I want to insert here:

 @if(Auth::check() && ($match->status == 'open' && $match->schedule < Carbon\Carbon::now() && Auth::user()->getMatchBetAmount($match->id) <= 0))

any ideas?



via Chebli Mohamed

How to set validation language depending on user type Laravel

I have three user types in my application and if the user type is user, validation messages should be English, otherwise if admin or a company, it should be Japanese.

In my app.php file I do:

'locale' => 'en',
'fallback_locale' => 'ja',

And in my web.php file:

Route::group(['middleware' => 'auth:user'], function () {
    App::setLocale('en');
    //user controllers
});

Route::group(['middleware' => 'auth:company'], function () {
    App::setLocale('ja');
    //company controllers
});

Route::group(['middleware' => 'auth:admin'], function () {
    App::setLocale('en');
    //admin controllers
});

When I didn't set the locale language of admin to ja, validation of user is English and the same with the admin and company. Now I set locale of admin and company to ja, the validation messages of users are now also Japanese. This is the validation files languages directory.

enter image description here

I really run out of ideas where to strike this one out and any help is appreciated. I've tried the suggested solutions in the web but nothing is working.



via Chebli Mohamed

XERO - Larael Integration

I installed the package using composer, and created a app/fascades/Xeroapi.php file. (https://github.com/calcinai/xero-php).

When I run the site, I get this error Argument 1 passed to XeroPHP\Application\PrivateApplication::__construct() must be of the type array, null given, called in: C:\xampp\htdocs\assignment_Sem1\app\Facades\XeroApi.php on line 76.

I have also created the demo App in the Xero and have my Private/Public key. The app created here is the private and have also uploaded the certificate file to Xero.

Not sure how to do this, as I am trying Laravel with Xero for the first time.

config.php

'xero_base_config' => [

    'xero' => [
        // API versions can be overridden if necessary for some reason.
        //'core_version'     => '2.0',
        //'payroll_version'  => '1.0',
        //'file_version'     => '1.0'
    ],
    'oauth' => [
        'callback'    => 'http://sz.com',
        'consumer_key'      => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'consumer_secret'   => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        //If you have issues passing the Authorization header, you can set it to append to the query string
        //'signature_location'    => \XeroPHP\Remote\OAuth\Client::SIGN_LOCATION_QUERY
        //For certs on disk or a string - allows anything that is valid with openssl_pkey_get_(private|public)
          'rsa_private_key'  => 'file://ABSOLUTE_PATH_TO_YOUR_PROJECT/html/certs/privatekey.pem'
    ],
    //These are raw curl options.  I didn't see the need to obfuscate these through methods
    'curl' => [
        CURLOPT_USERAGENT   => 'XeroPHP Test App',
        //Only for partner apps - unfortunately need to be files on disk only.
        //CURLOPT_CAINFO          => 'certs/ca-bundle.crt',
        //CURLOPT_SSLCERT         => 'certs/entrust-cert-RQ3.pem',
        //CURLOPT_SSLKEYPASSWD    => '1234',
        //CURLOPT_SSLKEY          => 'certs/entrust-private-RQ3.pem'
    ]

app/controller/test

  public function testing(){


      $transaction = rand(1111,9999); # random for me
    $data = array(
            "Type" => "ACCREC", # Accounting received.
            "AmountType" => "Inclusive",
            "InvoiceNumber" => "LD".$transaction,
            "Reference" => "LD".$transaction." - Some reference", # small description ref
            "DueDate" => date('Y-m-d'), # date('Y-m-d', strtotime("+3 days")),
            "Status" => "AUTHORISED",
            "LineItems"=> array(
                                         # add some arrays with items. Now just one.
                    array(
                        "Description" => "Just another test invoice",
                        "Quantity" => "2.00",
                        "UnitAmount" => "250.00",
                        "AccountCode" => "200",
                        "TaxType" => 'OUTPUT2' # Tax in New Zealand
                    )
                )
        );

    # before create a invoice, you MUST TO CREATE A CONTACT
        $xero_tests = XeroApi::createInvoice('contact@email.com', $data);

        dd($xero_tests);


      }



via Chebli Mohamed

Return JSON response instead of 401 Blade file

I am using AuthBasic for APIauthentication in a Laravel project, I have this problem : when the API request authentication is invalid instead of displaying the json response it return the 401 default blade view template.

here is the cod:

app\Http\Middleware\AuthBasic.php

public function handle($request, Closure $next)
{   
    if (Auth::onceBasic()) {
        return response()->json(["message", "Authentication Required!"], 401);
    } else {
        return $next($request);
    }
}



via Chebli Mohamed

why return lavavel 5 utf-8 string as code

i have a problem with Laravel 5.7, when it return utf-8 string. you can the problem in the follows capture:

enter image description here



via Chebli Mohamed

Laravel API Illuminate\Foundation\Testing\TestResponse empty array when expecting single object

Why is it that from a unit test in Laravel if I do the following request, decode the json response, it comes back as an empty array:

$response = $this->get(route('api.inspections.get', [
    "id" => $inspection->id
]));

$apiInspection = $response->json(); # Empty array :(

Yet doing the most basic get request to that same URL gets me a nice json response.

$inspection = file_get_contents(route('api.inspections.get', [
    "id" => $inspection->id
]));
$inspection = json_decode($inspection); # The expected inspection stdClass

Thanks



via Chebli Mohamed

Laravel - retrieving attribute from within a model relationship in a blade view

I have created a relationship between products and users using a foreign key called "previous_owner". I can see when I dump the value that I'm passing to the view that the data I'm after is available under:

product->relations->product_owner->user->attributes->name

But how do I access it from within my view. I'm trying to loop through the products and then do something like:

or

But non of it works, keep getting:

" Trying to get property 'name' of non-object "

SCREEN GRAB OF THE OBJECT



via Chebli Mohamed

Trying to get property 'admin' of non-object

I am trying to avoid ordinary users to see what's in my dashboard but it says

Trying to get property 'admin' of non-object

When I try to Auth the user. Here what the error says:

enter image description here



via Chebli Mohamed

What's the easiest way of understanding when to use collections vs. model instances in Laravel?

In Laravel it's very confusing how there's ->first and ->first(), ->last and ->last(), and for relationships there's ->nameofyourrelationship and ->nameofyourrelationship(). Even still there's Model::find() and collection->find() . I find this amount of duplication very staggering and difficult to work with. This slows me down and lowers my satisfaction of working in the framework. Is there a good resource to sorting out these differences and making it less cumbersome to use Laravel?



via Chebli Mohamed

Update select options - [Vue warn]: Computed property "options" was assigned to but it > has no setter

I'm writing my first Laravel Vue component and I have this error in console.

[Vue warn]: Computed property "options" was assigned to but it has no setter.

I just miss to update the options of the second select with the updated values I have in this.countries.

After the change this.countries get updated but the values of the options of the country_id select are not changing. I've tried adding computed but I get this error.

What am I doing wrong?

<template>
    <div>
        <div class="form-group continent_id">    
            <select name="continent_id" v-model="continent_selected" id="continent_id" class="selectpicker" data-live-search="false" title="Pick a continent" v-on:change="getAllCountries(continents)">
                <option v-if="continents.length>0" v-for="continent in continents" v-bind:value="continent.id">
                    
                </option>
            </select>
        </div>

        <div class="form-group country_id">    
            <select name="country_id" v-model="country_selected" id="country_id" class="selectpicker" data-live-search="true" title="Pick a country">
                <option  v-for="(country, index) in countries" v-bind:value="country.id" >
                    
                </option>
            </select>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
            this.loadData();
            console.log('Loaded datas.');
            console.log(this.continents);
            console.log(this.countries);
        },
        created(){
            //this.loadData();
        },
        data() {
            return {
                continents: [],
                countries: [],
                continent_selected: '',
                country_selected: '',
            }
       },
       computed: {
            options: function(event) {
               return this.countries
            }
        },

       methods: {
            loadData: function() {
                axios.get('/api/continents')
                .then((response) => {
                    // handle success
                    this.continents = response.data.data;
                    this.getAllCountries(this.continents);
                })
                .catch((error) => {
                    // handle error
                    console.log(error);
                })
                .then(() => {
                    // always executed
                });
            },
            getAllCountries: function(continents) {
                console.log(this.continent_selected);
                console.log(continents);

                var j = 0;
                this.countries = [];

                for (var i = 0, len = continents.length; i < len; i++) {

                    if (!this.continent_selected){
                        for (var key in continents[i].active_countries) {
                            this.countries[j] = {id: continents[i].active_countries[key], name: key};
                            j++;
                        }
                    }
                    else{
                        console.log("continent selected: "+ this.continent_selected);
                        for (var key in continents[i].active_countries) {
                            if (continents[i].id == this.continent_selected){
                                this.countries[j] = {id: continents[i].active_countries[key], name: key};
                                j++;
                            }
                        }
                        this.options = this.options;
                    }
                }
            }
        },
    }
</script>



via Chebli Mohamed

There is no existing directory storage/logs and its not buildable: Permission denied

I'm having a trouble right now. I am deploying my laravel project to a subdomain. It works for my other project, but this one will goes error for everything I tried.

There is no existing directory at "/Applications/XAMPP/xamppfiles/htdocs/SolisTimeReport/storage/logs" and its not buildable: Permission denied

From the error I found that the directory mentioned above is no longer available because it is in my local directory.

I'm using Laravel 5.7.8 with PHP 7.2 as default setting at the shared hosting. I don't get it what to do with it at this point. Please help.



via Chebli Mohamed

Laravel Reading files in storage

I have saved images in a file in the storage. I would like to get the files saved into an array using exec command in the controller and then pass the array into the blade. Is there any way to do it?



via Chebli Mohamed

Expected response code 354 but got code "554"

Expected response code 354 but got code "554", with message "554 5.5.1 Error: no valid recipients ". I am getting this error.

MAIL_DRIVER=smtp
MAIL_HOST=mail.example.net
MAIL_PORT=587
MAIL_USERNAME="noreply@example.com"
MAIL_PASSWORD="password"
MAIL_ENCRYPTION=tls

How to solve this issue.



via Chebli Mohamed

Why does laravel \Storage::store method cause this error?

In my local environment why I do following, it works.

    if( $request->file ){

        $path = $request->file('file')->store('public/chat/files');

        $mime_type = $request->file('file')->getMimeType(); 


        if( strstr( $mime_type, 'video' ) ){
            $data['message_type'] = 'video';
        }else if( strstr( $mime_type, 'image' ) ){
            $data['message_type'] = 'image';
        }else if( strstr( $mime_type, 'audio' ) ){
            $data['message_type'] = 'audio';
        }

But on apache running on Digital Ocean droplet when I run the same code I get the following error.

[2019-02-26 11:45:48] local.ERROR: The file "" does not exist {"userId":3,"email":"user@user.com","exception":"[object] (Symfony\\Component\\HttpFoundation\\File\\Exception\\FileNotFoundException(code: 0): 
The file \"\" does not exist a$
[stacktrace]
#0 /var/www/html/plugin_love_api/vendor/symfony/http-foundation/File/File.php(79): Symfony\\Component\\HttpFoundation\\File\\MimeType\\MimeTypeGuesser->guess('')
#1 /var/www/html/plugin_love_api/vendor/symfony/http-foundation/File/File.php(58): Symfony\\Component\\HttpFoundation\\File\\File->getMimeType()
#2 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Http/FileHelpers.php(60): Symfony\\Component\\HttpFoundation\\File\\File->guessExtension()
#3 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php(35): Illuminate\\Http\\UploadedFile->hashName()
#4 /var/www/html/plugin_love_api/app/Http/Controllers/ChatController.php(71): Illuminate\\Http\\UploadedFile->store('public/chat/fil...')
#5 [internal function]: App\\Http\\Controllers\\ChatController->sendMessage(Object(Illuminate\\Http\\Request))
#6 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)
#7 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction('sendMessage', Array)
#8 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Routing/Route.php(219): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(App\\Http\\Controllers\\ChatController), 'se$
#9 /var/www/html/plugin_love_api/vendor/laravel/framework/src/Illuminate/Routing/Route.php(176): Illuminate\\Routing\\Route->runController()
#10

PHP version is : PHP 7.2.15-0ubuntu0.18.04.1 (cli) (built: Feb 8 2019 14:54:22) ( NTS )

Also I have set 777 permissions on storage folder and all it's descendants.



via Chebli Mohamed

How to get rid of this error(array_key_exists() expects parameter 2 to be array, null given) in laravel

I use the libraray Edujugon\PushNotification for push Notification but it give me the error.

array_key_exists() expects parameter 2 to be array, null given

Please help me Here is my code. I do not know where i make a mistake. thanks in advance

public function likeActivity(Activity $activity)
{
    $authUser = JWTAuth::parseToken()->toUser();

    $authUser->likeActivity($activity);

    if ($activity->user_id != $authUser->id) {
        $user = User::where('id', $activity->user_id)->first();

        $push = new PushNotification('apn');
        $push->setMessage([
            'aps' => [
                'alert' => $authUser->name.' like your "'.$activity->activity_type.'"'.$activity->activity_title,
                'sound' => 'default',
                'badge' =>  $user->unreadNotifications->count()

            ],
            'extraPayLoad' => [
                // 'user' => $authUser,
                // 'post' => $post->id,
                'notification_type' => "Like Your Activity",
            ]
        ]);
        $push->setDevicesToken($user->deviceToken);
        $push->send();
        $feedback = $push->getFeedback();

        $user->notify(new LikedTheActivity($authUser, $activity));
    }

    return response()->json(['user'=> $authUser], 200);
} 



via Chebli Mohamed

Why error subscribing to specific mailchimp list

In my laravel 5.7 app I make subscribe/unsubscribe to lists of mailchimp using https://github.com/spatie/laravel-newsletter It works when ok and all users are suscribed to the current mailchimp list, which is described in .env file

MAILCHIMP_APIKEY = NNNNNNNNNN
MAILCHIMP_LIST_ID = NNNNNNNNNN  # ID of 'subscribers' mailchimp list

But as my site has several group news I try subscribe to mailchimp list with code :

$retData= Newsletter::subscribe($userProfile->email, ['FNAME'=>$userProfile->first_name, 'LNAME'=>$userProfile->last_name], 'subscribers'); // 3rd parameter can be different

where 3rd parameter is mailchimp list name, as I see it on the server as : https://prnt.sc/mqbgnb But I got error :

There is no list named `subscribers`.

Why error? Misconfiguring of of this mailchimp list ? It has some options, I am not sure if some of them is related to my issue ?

In doc I read as :

//Subscribe someone to a specific list by using the third argument:
Newsletter::subscribe('nanny.ogg@discworld.com', ['firstName'=>'Nanny', 'lastName'=>'Ogg'], 'Name of your list');

How to fix my error ?

Thanks!



via Chebli Mohamed

Laravel-5.6 'LIKE' in where select

I use this query and i get a error :

 $description = $request->get('description');
        if (!empty($description)){
        $description_query = Transcationhistorique::where(['sender_id' => $user_id, "%$description%", 'LIKE','description'])
            ->orWhere('receiver_id', $user_id)->get();
        }else{
            $description_query  =  "" ;
        }

and this is the error that I get :

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from transcation_historique where (sender_id = 32 and 0 = %salaire% and 1 = LIKE and 2 = description) or receiver_id = 32)"

and this what really i want to run:

select * from `transcation_historique` where (`sender_id` = 32 and `description` = %salaire%) or `receiver_id` = 32)



via Chebli Mohamed

How can i create laravel blade template programetically

How can i create laravel blade template programetically also need to include master page to it,need to save as new blade template inside views folder



via Chebli Mohamed

Axios unbale to catch error when server sends 422 in try-catch bloc

I'm using axios for my HTTP with Vue.js.But when I do the ajax call, everything goes well when server sends back response data with 200 success. But when there is errors,server does not execute the catch bloc. Here is my ajax call in Vue.js

export default{
    data(){
        return {
            form:{
                email:'',
                password:'',
                password_confirmation:'',
                fname:'',
                lname:'',
                city:''
            },
            formError:''
        }
    },
    methods:{
        //This should be a POST method through axios
        register:async function(){
           try{
               const res=await axios.post('api/register',this.form);
               console.log("Ba donnees : ",res.data);
           }catch(err){
               console.log("Erreeer",err.response);
           }
        }
    }
}

And here is my register controller:

private function validateForm($data){
        return Validator::make($data,
        [
            'fname' => ['required', 'string','min:2' ,'max:255'],
            'lname' => ['required', 'string','min:2' ,'max:255'],
            // 'mname' => ['string','min:2' ,'max:255'],
            'company' => ['string','min:2' ,'max:255'],
            'title' => ['string','min:2' ,'max:255'],
            'phone_number' => ['string','min:13' ,'max:13'],
            'city' => ['required', 'string','min:2' ,'max:100'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed']
            // 'password_confirm'=>['required','string']
        ]
      )->validate();
    }
    //Register
    public function register(Request $request){
        $data=$this->validateForm($request->all());
        $data['password']=Hash::make($data['password']);
        $user=new User($data);
        $user->save();
        return response()->json($user);

    }

When everything goes fine, I get the expected result of my try but in case of POST http://localhost:5000/api/register 422 (Unprocessable Entity) the is trying to log the statement in try.

But when I go in the network tab, I see the returned error JSON like this

{"message":"The given data was invalid.","errors":{"fname":["The fname field is required."],"lname":["The lname field is required."],"city":["The city field is required."],"email":["The email field is required."],"password":["The password field is required."]}}



via Chebli Mohamed

Select data and use where and where laravel 5.6

I am trying to create ( (Where and Where) OR (Where and Where) ) And after a lot of searching I found this

  $last_transations = Transcationhistorique::where('sender_id', '=', $user_id)->where('receiver_id','=', $user_id)
            ->orderBy('created_at', 'desc')->skip(3)->take(3)->get();

I get a empty result

"last 3 transactions": []



via Chebli Mohamed

Laravel 5.4 - Task scheduler withoutOverlapping() Running locally, but not on server

I have set up tasks on kernel.php. I have set up a similar debian environment locally, and the tasks are running as expected. However, on the server, tasks are not running if withoutOverlapping() method is given. If withoutOverlapping() is not given, tasks are running as expected.

Current configuration on kernel.php

$schedule->command('perform:task_one')->withoutOverlapping()->everyFiveMinutes();

Task is not fired at all. If I remove withoutOverlapping, task is fired. I have implemented withoutOverlapping as my task involves some mailing and may consume time at instances.



via Chebli Mohamed

Unable to add spatie/laravel-sluggable package in laravel 5.4.36

I am new to Laravel, I tried to add spatie/laravel-sluggable in my setup but faced this error in the terminal. I tried to search this but didn't find any relevant solution.

Any help will be appreciated.

here is the error:

Problem 1
    - Conclusion: remove laravel/framework v5.4.36
    - Conclusion: don't install laravel/framework v5.4.36
    - spatie/laravel-sluggable 2.1.0 requires illuminate/database ~5.5.0 -> satisfiable by illuminate/database[v5.5.0, v5.5.16, v5.5.17, v5.5.2, v5.5.28, v5.5.33,
v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44].
    - spatie/laravel-sluggable 2.1.5 requires illuminate/database ~5.5.0|~5.6.0|~5.7.0 -> satisfiable by illuminate/database[5.7.17, 5.7.18, 5.7.19, v5.5.0, v5.5.1
6, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v
5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.24, v5.6.25, v5.6.26, v5.6.27, v5.6.28, v5.6.29, v5.6.3, v5.6
.30, v5.6.31, v5.6.32, v5.6.33, v5.6.34, v5.6.35, v5.6.36, v5.6.37, v5.6.38, v5.6.39, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9, v5.7.0, v5.7.1, v5.7.10, v5.7
.11, v5.7.15, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.23, v5.7.26, v5.7.27, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].
    - spatie/laravel-sluggable 2.1.6 requires illuminate/database ~5.5.0|~5.6.0|~5.7.0 -> satisfiable by illuminate/database[5.7.17, 5.7.18, 5.7.19, v5.5.0, v5.5.1
6, v5.5.17, v5.5.2, v5.5.28, v5.5.33, v5.5.34, v5.5.35, v5.5.36, v5.5.37, v5.5.39, v5.5.40, v5.5.41, v5.5.43, v5.5.44, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12,
    - don't install illuminate/database v5.5.0|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.16|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.17|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.2|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.28|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.33|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.34|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.35|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.36|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.37|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.39|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.40|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.41|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.43|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.5.44|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.6.0|don't install laravel/framework v5.4.36
    - don't install illuminate/database v5.6.1|don't install laravel/framework v5.4.36
    - Installation request for laravel/framework (locked at v5.4.36, required as 5.4.*) -> satisfiable by laravel/framework[v5.4.36].
    - Installation request for spatie/laravel-sluggable ^2.1 -> satisfiable by spatie/laravel-sluggable[2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6].


Installation failed, reverting ./composer.json to its original content.

I also tried to add illuminate/database but it also showed the same issue.



via Chebli Mohamed

Object of class Carbon\Carbon could not be converted to int LARAVEL

How do I implement if the schedule has been expired where in I want to return a status of "Match will start soon".

here is the code:

 @if($match->schedule > 0)
      &nbsp;<strong id="match_schedule">Match will start soon</strong>
 @endif

I tried :

@if($match->schedule > $match->schedule)
      &nbsp;<strong id="match_schedule">Match will start soon</strong>
@endif

but it doesn't work. any ideas?



via Chebli Mohamed

lundi 25 février 2019

How to format json data in laravel?

I need to format this data in html and css and get ride of the json format and show only text.

Displayed data:

{"id":"<h3>...............................................<h3><br \\> 
<h1>rzNC35gDNG6moR3w<h1>"}

Controller:

function requete()
{
    $id = Str::random();
    $res = '<h3>...............................................<h3>'
        ."<br \><h1>".$id.'<h1>';
    return response()->json(['id' => $res]);
}

View:

$(document).ready(function() {   
     $.ajax({
            url:"",                              
     });
});



via Chebli Mohamed

How new user when registered automatically follows a user in laravel

I want when user signup it follows a specific user automatically. How can i do this in laravel. Here is my code. Please help thanks in advance

public function signUp(RegisterUser $request)
{
    if($profile_picture = $request->hasFile('profile_picture')) {
        $profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
        $request->profile_picture->move(public_path('ProfileImages'), $profile_picture);
        $profile_picture = 'ProfileImages/'.$profile_picture;
    } else {
        $profile_picture = NULL;
    }

    $user = User::create([
        'firstname' => $request->input('firstname'),
        'lastname' => $request->input('lastname'),
        'email' => $request->input('email'),
        'password' => bcrypt($request->input('password')),
        'password_changed_at' => Carbon::now()->toDateTimeString(),
        'username' => $request->input('username'),
        'profile_picture' => $profile_picture,
        'email_verification_token' => str_random(50),
    ]);

    if (!$user) {
        return response()->json(['failed to create new user'], 500);
    }

    $token = JWTAuth::fromUser($user);

    $userDetail = $user->where('id', $user->id)->with(['posts', 'buckets','likes', 'followers', 'following'])->withCount('posts', 'buckets','likes', 'followers', 'following')->first();

    $this->verifyEmail($user);

    $id = 9;
    $userFollow = User::find($id);
    dd($userFollow);
    $user->follow($userFollow);

    // return response()->json(['message' => 'Please Check your email to verify your account Or Login to Kindmill']);
    return response()->json(['token' => $token, 'user' => $userDetail], 200);
}

Here in this way i can do but cannot work. Please help



via Chebli Mohamed

Laravel React Uploading Files within a Form

So I am trying to implement an upload page within my app and in that page, you can have both an image and a song uploaded as well as other things (genre, description, etc). I managed to get the image to work using image intervention but i am trying to get my mp3/wav file (using a base64 decode function) to be read as a file so I can use the move method to store it in a local folder (valid upload) and I don't understand why laravel is reading it as a string. Is there something i'm missing?

the decoding function

function base64_to_song($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );

// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode($data[1]));

// clean up the file resource
fclose( $ifp ); 

return $output_file; 
}

In my controller:

$songextension = $request->get('songextension');
$file = $request->json()->get('song_file');
$extension = $songextension; 
$filename = rand(11111,99999).'.'.$extension;
$newfile = base64_to_song($file, $filename);
$destinationPath="uploads/music";
$newfile->move($destinationPath, $filename);

It just keeps reading $newfile as a string rather than the output



via Chebli Mohamed

Laravel 5.7 - How to retrieve data from an API with a axios.get?

I'm trying to get data from an API in a Laravel Vue component. I get this error in the console:

TypeError: Cannot set property 'continents' of undefined

What am I missing?

This is my code:

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
        },
        created(){
            this.loadData();
        },
        data() {  
            return {
                continents: [],
            }
       },
       methods: {
            loadData: function() {
                axios.get('/api/continents')
                  .then(function (response) {
                    // handle success
                    console.log(response.data);
                    this.continents = response.data;
                  })
                  .catch(function (error) {
                    // handle error
                    console.log(error);
                  })
                  .then(function () {
                    // always executed
                  });
            },       
        },  
    }
</script>



via Chebli Mohamed

One form is working while other form is not working in laravel 5.4

I've UserController in which I've two options -

  1. For Updating Profile
  2. For Updating Password

    namespace App\Http\Controllers;

    use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\User; use Auth; use Hash;

    class UserController extends Controller { public function profile(){ return view('profile', array('user' => Auth::user())); }

    public function update_avatar(Request $request){
        if(isset($request->avatar) && $request->avatar->getClientOriginalName()){
            $ext = $request->avatar->getClientOriginalExtension();
            $file = date('YmdHis').rand(1,99999).'.'.$ext;
            $request->avatar->storeAs('public/avatar',$file);
    
        }
        else
        {
            $user = Auth::user();
            if(!$user->avatar)
                $file = '';
            else
                $file = $user->avatar;
        }
        $user = Auth::user();
            $user->avatar = $file;
            $user->name = $request->name;
            $user->email = $request->email;
            $user->mb_number = $request->mb_number;
            $user->home_town = $request->home_town;
            $user->save();
    
        return view('profile', array('user' => Auth::user()));
    
    }
    
    public function update_password(Request $request){
        $user = Auth::user();
        if(Hash::check(Input::get('old_password'), $user['password']) && Input::get('new_password') == Input::get('confirm_new_password')){
            $user->password = bcrypt(Input::get('new_password'));
            $user->save();
        }
        return view('profile', array('user' => Auth::user()));
    }
    
    

    }

In my view blade, I've two forms -

  1. update_avatar for updating profile like name, phone number and avatar.
  2. update_password for updating password.

            </div>
            <div class="widget-user-image">
              <img class="img-circle" src="" alt="User Avatar">
    
            </div>
            <div class="box-footer">
              <div class="row">
                <div class="col-sm-4 border-right">
                  <div class="description-block">
                    <h5 class="description-header"></h5>
                    <span class="description-text">Email</span>
                  </div>
                  <!-- /.description-block -->
                </div>
                <!-- /.col -->
                <div class="col-sm-4 border-right">
                  <div class="description-block">
                    <h5 class="description-header"></h5>
                    <span class="description-text"></span>
                  </div>
                  <!-- /.description-block -->
                </div>
                <!-- /.col -->
                <div class="col-sm-4">
                  <div class="description-block">
                    <h5 class="description-header"></h5>
                    <span class="description-text">Phone No.</span>
                  </div>
                  <!-- /.description-block -->
                </div>
                <!-- /.col -->
              </div>
              <!-- /.row -->
            </div>
            <!--
            <div class="box-footer no-padding">
              <ul class="nav nav-stacked">
                <li><a href="#">Projects <span class="pull-right badge bg-blue">31</span></a></li>
                <li><a href="#">Tasks <span class="pull-right badge bg-aqua">5</span></a></li>
                <li><a href="#">Completed Projects <span class="pull-right badge bg-green">12</span></a></li>
                <li><a href="#">Followers <span class="pull-right badge bg-red">842</span></a></li>
              </ul>
            </div>
            -->
          </div>
          </div>
    
              <section class="content">
                <div class="container-fluid">
                    <form action="/profile" enctype="multipart/form-data" method="POST">
                        <div class="form-group">
                            <div class="form-group">
                                <label for="name">Name</label>
                                <input type="text" name="name" class="form-control" id="name" placeholder="Title" value="">
                            </div>
                            <div class="form-group">
                                <label for="email">Email</label>
                                <input type="text" name="email" class="form-control" id="email" placeholder="Description" value="" readonly>
                            </div>
                            <div class="form-group">
                                <label for="mb_number">Mobile No.</label>
                                <input type="text" name="mb_number" class="form-control" id="mb_number" placeholder="Schedule" value="">
                            </div>
                            <div class="form-group">
                                <label for="home_town">Home Town</label>
                                <input type="text" name="home_town" class="form-control" id="home_town" placeholder="Deadline" value="">
                            </div>
                            <div class="form-group">
                                <label>Update Profile Image</label>
                                <input type="file" name="avatar">
                                @if($user->avatar)
                                <img src="" style="width:150px;">
                                @endif
                            </div>
                        <input type="hidden" name="_token" value=""
                        <a href="" type="submit" class="btn btn-info"></a>
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                </div>
    </section>
    
    <section class="content">
                <div class="container-fluid">
                    <form action="/profile" enctype="multipart/form-data" method="POST">
                        <div class="form-group">
                            <div class="form-group">
                                <label for="old_password">Old Password</label>
                                <input type="password" name="old_password" class="form-control" id="old_password" placeholder="Old Password">
                            </div>
                            <div class="form-group">
                                <label for="new_password">New Password</label>
                                <input type="password" name="new_password" class="form-control" id="new_password" placeholder="New Password">
                            </div>
                            <div class="form-group">
                                <label for="confirm_new_password">Confirm New Password </label>
                                <input type="password" name="confirm_new_password" class="form-control" id="confirm_new_password" placeholder="Confirm New Password">
                            </div>
                        <input type="hidden" name="_token" value=""
                        <a href="" type="submit" class="btn btn-info"></a>
                        <button type="submit" class="btn btn-primary">Update Password</button>
                    </div>
                </div>
    </section>
    
    

update_password function is working fine but update_avatar function is not working neither it's showing any error. I've tried dd($user) but still not giving output to dd.



via Chebli Mohamed

laravel view composer - send foreach data to view blade

ok been messing with this for a few hours now, just can't seem to figure it out. I am collecting data from certain users, then I want print out all the data and send it to the view blade for each user.

my code so far

        view()->composer('dashboard.index', function (View $view) {
        $currency = Config::whereKey('currency')->first()->value;
        $user = auth()->user();

        $users = User::select('id','name','type','pay_rate','country_id')
        ->where('type', '=', 'country_manager')
        ->orderBy('country_id','ASC')
        ->get();

        if($users) {
           foreach ($users as $u) {
            $uid = $u->id;
            $name = $u->name;
            $type = $u->type;
            $pay = $u->pay_rate;
            $countryid = $u->country_id;

            if($type == 'country_manager'){ $role = 'Country Manager'; }
            if($type == 'team_leader'){ $role = 'Team Leader'; }
            if($type == 'moderator'){ $role = 'Moderator'; }
            if($type == 'suspend'){ $role = 'Suspended'; }    

            $sent = '0';
            $reply = '0';
            $earn = '0';

            $data = '<div class="divTableCell">'.$name.'</div>
            <div class="divTableCell">'.$countryid.'</div>
            <div class="divTableCell">'.$role.'</div>
            <div class="divTableCell">'.$pay.' '.$currency.'</div>
            <div class="divTableCell">'.$sent.'</div>
            <div class="divTableCell">'.$reply.'</div>
            <div class="divTableCell">'.$earn.' '.$currency.'</div>';


            }
        }

    $view->with(compact('data'));

    });

I know the data is collecting correctly, but just do not know how to print it view page from the view composer script.



via Chebli Mohamed

restore a statamic app from existing folder

I need to open a directory where is installed statamic in my local macbook the server web open but without image css only with the text like the picture

enter image description here

maybe the problem is in the configuration file but i dont have idea where is in the folder app

im newbie also about laravel

sorry for the english i hope that they understand anyone help me ? thanks a lot



via Chebli Mohamed

Get user rank position based on total score and time

I want to get user rank position based on the total score and average time. but the query I am using its provide wrong postion number

$myId = TotalScore::where('user_id', $user_id)->first();
$position = TotalScore::where('ts', '>=', $myId->ts)->where('avg_times_taken', '>=', $myId->avg_times_taken)->count();

this is the code I am using.

enter image description here

this is the table structure I am using.



via Chebli Mohamed

Laravel 5.7: Is API request or not?

Hi I am working on a project, and I want to use the same Controller for both API and WEB, is there a function that can tell whether it is a API request or Web ?



via Chebli Mohamed

Laravel validation errors doesn't work properly - localization issue

I have several languages on my application and I'm using laravellocalization package (Here is github page)

Well package works fine, I checked both of Laravellocalization::getCurrentLocale() and App::getLocale(). Both of them gave me correct locale..

But still when some validation errors occured, it shows error in different languages. Sometimes it uses correct locale but sometimes it shows with not the default locale but Request::getPreferredLanguage()

I don't know what causing it and how to I fix it. Log file shows anything, when dump the locales, everything seems just fine..

How can I solve this issue ?



via Chebli Mohamed