dimanche 31 janvier 2021

Laravel execute where condition based on variable null or not

I am new to laravel. I want to execute my where condition if my variable value is not null. I tried the below code exactly not getting an idea of what to do.

$search = $array['search'];
$id = $array['id'];
$Data = Model::where('id', '=', $id)

if($search != '') {
    //I want to include where condition here
}


via Chebli Mohamed

vendredi 29 janvier 2021

Laravel echo server chat message notification update only one time

I have a website built with Laravel 5.8 and it has real time (socket ) chat on it. The problem is when I send a message from one client, another client got a notification unless you go to chat window. Once you read a message then it is not going to be updated anymore unless you make hard refresh of web page.

This issue happens when I use Redis, Socket.io, Laravel-echo Server. But everything works great when I change it to Pusher as a broadcast provider.

My chatcontroller.php is like below :

<?php

namespace App\Http\Controllers;

use App\Http\Resources\Chat as ChatResource;
use App\Http\Resources\MarketplaceTrade as MarketplaceTradeResource;
use App\Models\Chat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class ChatController extends Controller
{
    /**
     * Get chat resource
     *
     * @param Chat $chat
     * @return ChatResource
     */
    public function get(Chat $chat)
    {
        if (!$chat->shouldAllowUser(Auth::user())) {
            abort(403, trans('chat.access_forbidden'));
        }

        $chat->load([
            'participants' => function ($query) {
                $query->where('user_id', '!=', Auth::user()->id);
            },
            'participants.user'
        ]);
        return new ChatResource($chat);
    }

    /**
     * Update user's participation.
     *
     * @param Chat $chat
     */
    public function updateParticipation(Chat $chat)
    {
        if (!$chat->shouldAllowUser(Auth::user())) {
            abort(403, trans('chat.access_forbidden'));
        } else {
            $chat->updateParticipation(Auth::user());
        }
    }

    /**
     * @param Chat $chat
     * @return MarketplaceTradeResource
     */
    public function latestMarketplaceTrade(Chat $chat)
    {
        if (!$chat->shouldAllowUser(Auth::user())) {
            abort(403, trans('chat.access_forbidden'));
        }

        $trade = $chat->marketplaceTrades()
            ->latest()->with('buyer', 'seller')
            ->first();

        return new MarketplaceTradeResource($trade);
    }

    /**
     * Get status of chat for authenticated user
     *
     * @param Chat $chat
     * @return array
     */
    public function participation(Chat $chat)
    {
        if (!$chat->shouldAllowUser(Auth::user())) {
            abort(403, trans('chat.access_forbidden'));
        }

        return $chat->getParticipation(Auth::user());
    }

    /**
     * Return paginated result of authenticated chat
     *
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function table(Request $request)
    {
        $chats = Auth::user()
            ->participatingChats()->latest('updated_at')
            ->with([
                'participants' => function ($query) {
                    $query->where('user_id', '!=', Auth::user()->id);
                },
                'participants.user'
            ]);
   

        $filters = $request->get('filters', []);

        if (array_has($filters, 'user') && $filters['user']) {
            $chats->whereHas('participants.user', function ($query) use ($filters) {
                $query->where('id', '!=', Auth::user()->id);
                $query->where('name', 'like', "%{$filters['user']}%");
            });
        }

        $results = paginateResult(
            $chats,
            $request->get('itemPerPage', 10),
            $request->get('page', 1)
        );

        return ChatResource::collection($results);
    }
}

I have found that second client which should get a notification gets a notification normally when I remove this part :

->with([
                'participants' => function ($query) {
                    $query->where('user_id', '!=', Auth::user()->id);
                },
                'participants.user'
            ]);

is there a way to make it work without deleting this part? Because when I remove this part chat page not working although chat notifications work properly.



via Chebli Mohamed

Laravel5: wizard is accessible publicly without authentication [closed]

I have an application that is in laravel 5 framework and there is a wizard that is placed out of the framework. Which is publicly accessible. How can I make the wizard only accessible when the user is logged in on my application.



via Chebli Mohamed

How to load another Console/Kernel.php in Laravel project?

I have a running Laravel application which has the default Console/Kernel.php where all my scheduled commands are defined as usual.

But now I have another Laravel application that I am trying to merge with this existing application, and I have created a folder inside the existing Laravel application and I am using a Service Provider to load all the things. This way I can keep the code of the two projects separate but at the same time all features under the same repository.

<?php

namespace SecondApp;

use Illuminate\Support\ServiceProvider;

class SecondAppServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        include __DIR__ . '/routes/web.php';
        include __DIR__ . '/routes/api.php';

        $this->app->register('SecondApp\App\Providers\AppServiceProvider');
        $this->app->register('SecondApp\App\Providers\AuthServiceProvider');
        $this->app->register('SecondApp\App\Providers\BroadcastServiceProvider');
        $this->app->register('SecondApp\App\Providers\EventServiceProvider');
        $this->app->register('SecondApp\App\Providers\JobServiceProvider');
        $this->app->register('SecondApp\App\Providers\MailerServiceProvider');
        $this->app->register('SecondApp\App\Providers\RouteServiceProvider');
        $this->app->register('SecondApp\App\Providers\StorageServiceProvider');
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadMigrationsFrom(__DIR__ . '/database/migrations/');

        $this->publishes([
            __DIR__ . '/config/' => config_path()
        ], 'second-app-config');

        $this->publishes([
            __DIR__ . '/resources/' => base_path('resources')
        ], 'second-app-resources');
    }
}

This is what my service somewhat looks like. Everything else seems to work well, roues, migrations, registering service providers and so on, but this second project now also has Console/Kernel.php file. And those commands are not being called yet, obviously because laravel doesn't know about it. So I am wondering how can I tell Laravel to look at that as well? Is this possible, or will I have merge the code into one main Kernel.php?

I have the same question about Http/Kernel.php as well, but I am sure if someone can suggest how to make one work, I can make the other work as well.



via Chebli Mohamed

number_format() behavior is not as expected in php

i have make helper function for getting value by using number_formate()

 function getRatePrecision($rate)
    {
        return number_format((float)$rate, (int)getSingleOrganisationSetting('default_rates_percision'));
    }

I am passing value to this function to use number_format() there is another function getSingleOrganisationSetting('default_rates_percision') which is getting value from database which I need after . for example if it is 24.8888 it will convert it to 24.9 . But weirdly it is converting. it is converting 10687 to 10 which doesn't make sense. obviously this is error from my end but I can't figure it out why.



via Chebli Mohamed

jeudi 28 janvier 2021

Laravel: Private wizard accessible without authentication

I have front-end in angular and backend in laravel5. There are two wizards. One is that on which I log in and I can access all of its functionality and the other one is UI is integrated with this one. I just want to access the second UI only when I'm login into my first UI. The second UI code is placed out of scope of laravel how can I achieve it? Can anyone help me on this?



via Chebli Mohamed

php strlen returning incorrect values

I'm using laravel 5.7, and i decided to play with some strings, here comes my problem, basically, my code in my controller goes like this.

$from = strlen($request->from);

$to  = strlen($request->to);
  
return array('from_len' => $from, 'to_len'=>$to);

what I'm sending in postman is like this

"direction" : true,
"to" : "",
"from" : "‬"

and what return is this

{
 "from_len": 3,
 "to_len": 0
}

So yeah i don't understand what is happening.

Thanks in advance for your attention people.



via Chebli Mohamed

can react js components and laravel blade work in one single project? if not, what's the best approach?

I have a project that is fully developed in laravel mvc design pattern, and now i want to change few of the blade files to react js components within the same project directory. what would be the best way to do that? so that whenever user views those pages, they should be appeared from react component, also i need to manage session stuff on these react components as well like logged-in user details etc...



via Chebli Mohamed

How to get specific columns from relation table in laravel?

I am trying to fetch soecific columns data from relational table but it is giving me null

$allConsignments = Consignment::query();
$allConsignments->select(['id','customer_reference'])->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get();

When I don't use select() then it gives correct data .

like this

$allConsignments = Consignment::query();
$allConsignments->with('customers:name,id')->orderBy('id', 'desc')->limit(5000)->get()

it is working but I also need specific columns from Consignment Table. what could be the reason?



via Chebli Mohamed

Two columns for password in Laravel for login

I have two password column one is password and other in temp_password, user can login with either password or temp_password for that i'm using following code:

if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
    echo "User Logged In";
} else if(Auth::attempt(['email' => request('email'), 'temp_password' => \Crypt::encrypt(request('password'))])) {
    echo "User Logged in";
} else {
    echo "Incorrect Credentials";
}

i'm getting this error :

Undefined index: password", exception: "ErrorException"

if i remove else if part it is working properly.

Any help is highly appreciated.



via Chebli Mohamed

mercredi 27 janvier 2021

How to insert and upload multiple file using laravel?

<h4 class="card-title">Add Product</h4>
<form class="forms-sample" action="" method="post" enctype="multipart/form-data">
    
    <div id="dynamicTable">
        <div class="row">
            <div class="col-md-4">
                <div class="form">
                    <label class="bmd-label-floating">Product Image</label>
                    <input type="file" name="product_image[]" class="form-control">
                </div>
            </div>
            <div class="col-md-2">
                <div class="form">
                    <button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus"></i></button>
                </div>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary pull-center">Submit</button>
</form>

<script type="text/javascript">
    var i = 0;
    $("#add").click(function(){
        ++i;
        $("#dynamicTable").append('<div class="row"><div class="col-md-4"><div class="form"><input type="file" name="product_image[]" class="form-control"></div></div><div class="col-md-2"><div class="form"><button type="button" class="btn btn-danger remove-tr"><i class="fa fa-minus"></i></button></div></div></div>');
    });
    $(document).on('click', '.remove-tr', function(){  
        $(this).closest(".row").remove();
    });  
</script>

function:

public function AddNewProduct(Request $request)
{
    $date=date('d-m-Y');
    $this->validate(
        $request, [
                    'product_image' => 'required',
                    'product_image.*' => 'mimes:jpeg,png,jpg',
                ]
        );

    if($request->hasfile('product_image'))
    {
        foreach($request->file('product_image') as $file)
        {
            $fileName = $file->getClientOriginalName();
            $fileName = str_replace(" ", "-", $fileName);
            $file->move('images/product/'.$date.'/', $fileName);
            $product_image[] = 'images/product/'.$date.'/'.$fileName; 
        }
    }

    echo "<pre>";
    print_r($product_image);
}

In the above code I am add multiple file dynamically via click on add button which is perfectly working now what happen when I click on submit button and I am trying to print multiple image then only 1 file is showing I don't now why? So, How can I upload multiple file and insert into database using laravel? Please help me.

Thank You



via Chebli Mohamed

File get contents too slow on 50 files

I need to copy existing private s3 files to another directory but my process is too slow, on my local its 2 seconds per file_get_content of each file.

My problem is most files that I process are 50+ files so if you total that would be 2seconds * 50 and its really not a great user experience waiting for that amount of time for a process to finish, what might be the best approach I can do to refactor this? queue is not really an option at the moment

foreach ($sourceAttachmentFiles as $sourceAttachmentFile) {

    $newFullFileName = $newDirectory.$sourceAttachmentFile->filename;
    
    // 2 seconds every loop
    $content = file_get_contents($sourceAttachmentFile->getS3SignedUrl());

    Storage::disk('s3')->put($newFullFileName, $content, 'private');
}


via Chebli Mohamed

When I submit my data to the text field it is not submitting

This is my Postcontroller code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {

        return "It's working".$id;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('posts.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request   $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        return $request->all();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        return "Show Controller ".$id;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    public function contact(){
        $people=['Snehal','Swarna','Rhitu','Mashuk','Sajid'];
        return view('contact',compact('people'));
    }
    public function show_post($id,$name,$password){
        return view('post',compact('id','name','password'));
    }
}

myroute https://i.stack.imgur.com/qLr0b.jpg

My Create view https://i.stack.imgur.com/DfIft.jpg



via Chebli Mohamed

mardi 26 janvier 2021

How to use multiple whereIn in laravel collection

I have a collection of arrays that I'm trying to return based on the $prices value that I passed in. $prices = ['100', '200'];

 $collection = collect([
   ['product' => 'Desk', 'price' => 100, 'price2' => 150],
   ['product' => 'Chair', 'price' => 150, 'price2' => 200],
   ['product' => 'Bookcase', 'price' => 300, 'price2' => 350],
   ['product' => 'Door', 'price' => 400, 'price2' => 200],
   ['product' => 'Door', 'price' => 450, 'price2' => 500],
 ]);

 $filtered = $collection->whereIn('price', $prices)->whereIn('price2', $prices);

 $filtered->all();

/* The result should return where price or price2 is 100 or 200:
  [
    ['product' => 'Desk', 'price' => 100, 'price2' => 150],
    ['product' => 'Chair', 'price' => 150, 'price2' => 200],
    ['product' => 'Door', 'price' => 400, 'price2' => 200],
  ]
*/


via Chebli Mohamed

Would like to filter the selection to a certain group id

Hello currently developing an online application system and now im in the module where the secretary would forward the applicant's information to specific board of interview panel. my code lets the secretary select from my tb_users table but i want it filtered to a specific group_id so not all users registered would show up on the selection

Here is my code used for the

$("#panelfirst").jCombo("{!! url('secretariat/comboselect?filter=tb_users:group_id:first_name|last_name') !!}",
        {  selected_value : '' });


via Chebli Mohamed

using both regular authentication and

So I want to have authentication via HTTP Basic Auth --and-- authentication which accepts a username / password via HTML. I also want the username / password combo to be different for each one. To that end I figured I'd use the following pre-built middleware:

  • Illuminate/Auth/Middleware/Authenticate
  • Illuminate/Auth/Middleware/AuthenticateWithBasicAuth

My question is... can I use both regular authentication authentication and HTTP Basic authentication at the same time whilst having a different username / password combo for both?



via Chebli Mohamed

How to get the records of different models with their relationships in a single query?

I make 3 queries, each query with its fields, some are the same, others are different fields, but in the end I want to obtain a single query, that is, to obtain a single arrangement of objects with all records

For which I have done it this way:

$query1 = Model1::query()->select('id','name','insurance_information');
$query2 = Model2::query()->select('id','name','insurance_information');
$query3 = Model3::query()->select('id','name','json_schema');

$query3 = $query3->unionAll($query1) 
          ->unionAll($query2 );

and it effectively brings me all the records of the models, but the problem is that the values ​​of the fields intersect. for example the records of Model1 ($query1) show the property 'json_schema' but 'json_schema' is only for the $query3

The same thing happens with relations, I can't get the relations from each record and ultimately join them into a single array of objects.

How could you perform this functionality



via Chebli Mohamed

Laravel 5 custom validation how to force fail

Works fine until I am expecting the validation to fail, even if return false appear the validation still doesn't work.

namespace App\Providers;

use Validator;

class AppServiceProvider extends ServiceProvider
{
       Validator::extend('cValidate',function($attribute, $value, $parameters, $validator) {
            $request = request()->all();

            $response = Utils::isClientActive($request['c'], $request['d'], $request['id']);

            if ($response->getData()) {return false;}

            return true;
        });
       Validator::replacer('cValidate', function($message, $attribute, $rule, $parameters) {
            return 'Error message';
        });
}

The validation rule appears in the validator object but no error seems to appear

$request = request()->all();
$validator = \Validator::make($request, 
['cups' => 'required|cValidate', ]);
 if ($validator->fails()) {
            return ["status" => false, "errors" => $validator->errors()->all()];
        } else {
            return ["status" => true];
 }


via Chebli Mohamed

laravel how to save files with predefined name

in laravel controller i am trying to give each video file i uploading should be rename as

**myfile.mp4**

and save in public folder.

but my present code makes random number for my files but i need to give name as myfile

my controller

$input['file_id'] = time() . '.' . $request->file_id->getClientOriginalExtension();
        $folder1 = public_path('/public');
        $path1 = $folder1 . $input['file_id']; // path 1
        $request->file_id->move($folder1, $input['file_id']);


via Chebli Mohamed

lundi 25 janvier 2021

adjusting laravel's timeout settings for basic access authentication

According to https://laravel.com/docs/7.x/authentication#http-basic-authentication Laravel supports basic HTTP authentication.

According to https://tools.ietf.org/html/rfc7235#section-6.2 "Clients that have been idle for an extended period, following which the server might wish to cause the client to re-prompt the user for credentials".

My questions is... can the length of this "extended period" be adjusted in Laravel? If so how would I do that? And what happens if a new Docker container is launched and then a client who had been connecting to one container suddenly connects to this new Docker container? Will the client be reprompted to login in that scenario? If so how could I make it so that it wouldn't do that?

I'm running Laravel 5.5.



via Chebli Mohamed

Laravel: Missing data after resource merge

I have two Laravel resources that have the same internal structure, for example:

{
    "data": {
        "object1": [
            "id": 1
            "foo" "bar"
            "items": [
                {
                    "name": "item1"
                    "color": "black"
                }
                {
                    "name": "item2"
                    "color": "blue"
                }
            ]
        ]
    }
}

Each resource has more than one object (i.e object1, object2, etc) and each resource has distinct key names than the other (no key name conflict).

When I return each resource independently, all the data show up as expected, but when I try to merge both (return $resource1->merge($resource2);, some data from resource one objects do not show (such as items)

What am I doing wrong?



via Chebli Mohamed

How to use laravel permissions in react front end?

I have set the ACL of the laravel application . I have developed role each role has specific permissions. In laravel blade it is very easy check permissions like this

@if(auth()->user()->hasPermission('customers','view'))

                            <li class="kt-menu__item " aria-haspopup="true">
                                <a href="" class="kt-menu__link ">
                                    <span class="kt-menu__link-icon"><i class="fa fa-users" aria-hidden="true"></i>
                                    </span>
                                    <span class="kt-menu__link-text">Customers</span>
                                </a>
                            </li>

                            @endif

How i can do this in react js ?



via Chebli Mohamed

laravel 5.8 echo server trying to auth non-existing channel

Alright so I had this private channel that I actually deleted a bit time ago, but it keeps on trying to authenticate it...

[3:17:38 PM] - EtqURfdxFGpzBmSmAAAA joined channel: public-channel-1
[3:17:41 PM] - Preparing authentication request to: http://localhost.php
[3:17:41 PM] - Sending auth request to: http://localhost.php/broadcasting/auth

[3:17:41 PM] - Error authenticating MhxVL-RaA6Ca7aN0AAAB for private-live-chat
Error: getaddrinfo ENOTFOUND localhost.php
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'http://localhost.php'
}
Error sending authentication request.

So I deleted the private-live-chat channel and I made public one but it keeps on trying to verify it...

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;

class NewMessageEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $username;
    public $message;

    /**
     * Create a new event instance.
     *
     * @param string $message
     * @param string $username
     */
    public function __construct(string $message, string $username)
    {
        $this->username = $username;
        $this->message = $message;
    }


    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('live-chat');
    }
}

I am using redis for this.



via Chebli Mohamed

Information about Log parsing a file

So I was parsing a file that updates every 5-10 minutes and the content of the file is stored in a database. The problem I am facing that every time the file is parsed it reads the whole file so the data that was read 10 mins ago and stored in the database is getting stored again. Please suggest ways to solve this problem



via Chebli Mohamed

Can't update existing data on database

The goal of the system is to update and create companion details on the same field. There is no problem in storing new data but it can't update the existing ones. What am I missing here?

here's my controller to store and edit data:

  public function update(UpdateInsuranceRequest $request, Insurance $insurance)

    $lastid = $insurance->id;
        if(count($request->companion_name) > 0)
        {
        foreach($request->companion_name as $comp=>$v){
            $data2=array(
                'insurance_id'=>$lastid,
                'companion_name'=>$request->companion_name[$comp],
                'ic'=>$request->ic[$comp],
                'dob'=>$request->dob[$comp],
                'relationship'=>$request->relationship[$comp]
            );
            if ($request->companion_id[$comp] <> '')
            {
                    $compaud=Companion:: where('insurance_id', $insurance->id)->first();
                    $compaud->update($data2);
            }
            else
            {
                Companion::insert($data2);
            }
        }
    }
return redirect()->route('admin.insurances.index');
}

my edit blade

<div class="card-body">
<input type="text" name="cn" value="">
@endforeach --}}
<table class ="table" id="companions_tb">
    <thead>                                   
        <tr>
            <th>Name</th>
            <th>Date of Birth</th>
            <th>IC No</th>
            <th>Relationship</th>
        </tr>
    </thead>
    <tbody>
        @foreach (old('companions', $companions->count() ? $companions : ['']) as $companion)
       
        <tr id="companion">
            <tr> 
            <td>
                <input type="hidden" name="companion_id[]" id="companion_id[]" class="form-control" value="" />
                 <input type="text" name="companion_name[]" id="companion_name[]" class="form-control" value="" />
            </td>

            <td>
                <div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-date-today-highlight="true" data-date-end-date="0d">
                <input class="form-control" name="dob[]" id="dob[]" value="">
                <div class="input-group-addon">
                <span class="fa fa-calendar"></span>
                </div>
                </div>
            </td>
            
            <td>
                <input type="text" name="ic[]" id="ic[]" class="form-control" value="" />
            </td>
            <td>
                <input type="text" name="relationship[]" id="relationship[]" class="form-control" value="" />
            </td>
        </tr>
        @endforeach
        <tr id="companion"></tr>
        <tr id="companion"></tr>
    </tbody>
</table>

<div class="row">
    <div class="col-md-12">
        <input type="button" class="addRow btn btn-default" value="+ Add Row">
        <input type="button" class="btn btn-danger remove" value="+ Remove Row">
    </div>
</div>

<script>
    $('.addRow').on('click',function(){
        addRow();
    });
    function addRow()
    {
        var tr='<tr>'+
        '<td><input type="hidden" name="companion_id[]" id="companion_id[]"><input type="text" name="companion_name[]" id="companion_name[]" class="form-control"></td>'+ 
        '<td><div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-date-today-highlight="true" data-date-end-date="0d"><input class="form-control" name="dob[]" id="dob[]" value=""><div class="input-group-addon"><span class="fa fa-calendar"></span></div></div></td>'+
        '<td><input type="text" name="ic[]" id="ic[]" class="form-control" value=""></td>'+
        '<td><input type="text" name="relationship[]" id="relationship[]" class="form-control" value=""></td>'+
        '</tr>'
        $('tbody').append(tr);
    };

</script>

database: enter image description here

what the view looks like:

enter image description here



via Chebli Mohamed

dimanche 24 janvier 2021

How to take column from two table in whereExists clause in laravel 5.5

I have three table 1)allcasefileofuserrequest 2)allscanfileofuserrequest 3)userrequestforcasecopies

a) userrequestforcasecopies->allcasefileofuserrequest has one to many relationship

b) userrequestforcasecopies->allscanfileofuserrequest has one to many relationship c)id(primary key) in userrequestforcasecopies -> request_id(foreign key) in allcasefileofuserrequest

d)id(primary key) in userrequestforcasecopies -> request_id(foreign key) in allscanfileofuserrequest

I want to write sql query such that in where exist clause get record from allcasefileofuserrequest and allscanfileofuserrequest where approved_status is 1.Below Is my query in laravel 5.5

DB::table('userrequestforcasecopies')
                                                               
 ->where('id',$requestId)
                                                         
 ->where('first_approved_status',2)
                                                               
 ->whereExists(function($query) use($requestId)
                                                                            
 {
                                                                                
  $query->from('allcasefileofuserrequest')
                                                                                       
  ->fullJoin('allscanfileofuserrequest')
                                                                                        
  ->where('request_id', $requestId)
                                                                                        
  ->where('approved_status',1)
                                                                                        
  ->select('request_id')
                                                                                        
  ->get();
                                                                                
  })
                                                                             
                                                                
 ->update(['second_approved_status'=> 1,
                                                                        
 'second_approved_status_done_at' => Carbon::now()->format('Y-m-d H:i:s'),
                                                                        
 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')

                                                                            
 ]);

But full join not work on laravel 5.5



via Chebli Mohamed

Cannot download laravel/socialite package in laravel 5.8

[ErrorException]
file_put_contents(/home/webwerks/.cache/composer/repo/https---repo.packagis
t.org/provider-psr~http-client.json): failed to open stream: Permission den
ied



via Chebli Mohamed

how to set trusted proxies for laravel 5.5

Quoting https://laravel-news.com/trusted-proxy

You can create the config/trustedproxy.php configuration by running vendor:publish:

php artisan vendor:publish --provider="Fideloper\Proxy\TrustedProxyServiceProvider"

I did that and altho it said "Publishing complete." I'm not seeing a config/trustedproxy.php file...

I did grep -r Fideloper . and that did not return any results either...

I'm running Laravel 5.5



via Chebli Mohamed

how is url.intended set?

My website In vendor/laravel/framework/src/Illuminate/Routing/Redirector.php there's this method:

    /**
     * Create a new redirect response to the previously intended location.
     *
     * @param  string  $default
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function intended($default = '/', $status = 302, $headers = [], $secure = null)
    {
        $path = $this->session->pull('url.intended', $default);

        return $this->to($path, $status, $headers, $secure);
    }

If $default is 'backend/backend' then $path winds up being http://mywebsite.com/backend/backend instead of https://mywebsite.com/backend/backend. ie. I want it to return https intsead of http.

I'm doing \URL::forceScheme('https'); in the service provider but it doesn't matter.

I see that the guest() method in Redirector.php sets url.intended but that method isn't being called.

I'm running Laravel 5.5.

Any ideas?



via Chebli Mohamed

Get all records from another table with pivot

I have three tables:

comments

id

comment_links

id | comment_id | link_id

links

id

I want to get all Links associated with each Comment. As you can see, CommentLink should act as a pivot table, but I don't know how to set up the relationships to make this work. I think I need to use the hasManyThrough relationship, but I'm not 100% sure.

Here are my current class relationships (they may be wrong):

Comment.php:

class Comment extends Model
{
    public function commentLinks()
    {
        return $this->hasMany('App\CommentLink', 'comment_id', 'id');
    }

    public function links()
    {
        // How do I fetch all links here using the pivot table?
    }
}

CommentLink.php:

class CommentLink extends Model
{
    public function comment()
    {
        return $this->belongsTo('App\Comment');
    }
    
    public function link()
    {
        return $this->hasOne('App\Link', 'id', 'link_id');
    }
}

Link.php:

class Link extends Model
{
    public function commentLinks()
    {
        return $this->belongsToMany('App\CommentLink', 'link_id', 'id');
    }
}

What do I need to do here to make this work?



via Chebli Mohamed

Route [x] not defined when using auth middleware

I am making a website with laravel but i am getting an error while using middleware auth. it says Route[x] not defined.error

i am using laravel 5.8 please some one help me



via Chebli Mohamed

PhpSpreadsheet \ Reader \ Exception Failed to load /root_dir/public/laravel-excel-fLRGTlw9uEE2XRz0k1fXdcg2wfs2RWy7.html as a DOM Document

I have tried everything for resolving this issue but nothing worked.

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

Also Updated my Dependencies

composer dump-auto -a
composer update

But Nothing of these things have helped me

Please respond some asap.



via Chebli Mohamed

wherebetween laravel not working with variable

I am using Laravel 5.8, and I would like to get rows between two prices in my database.

I using this code to get my product:

$prd = Product::where($args)->whereBetween('price', [$request->min_price, $request->max_price])->get();

But the problem is when I use the code above and I return $prd; nothing returned but when I put a static number as $request->min_price or $request->max_price it works correctly

I must set one of them as a static number like this:

$prd = Product::where($args)->whereBetween('price', [100, $request->max_price])->get();

or:

$prd = Product::where($args)->whereBetween('price', [$request->min_price, 1000])->get();

Where is my problem or mistake?



via Chebli Mohamed

samedi 23 janvier 2021

SQL returns syntax error from laravel raw

I'm trying to make a raw sql request to get all possible status from an enum column :

    public static function getPossibleStatuses(){
        $type = DB::select(DB::raw('show columns from defi_user where field = "category";' ))[0]->Type;
        preg_match('/^enum\((.*)\)$/', $type, $matches);
        $values = array();
        foreach(explode(',', $matches[1]) as $value){
            $values[] = trim($value, "'");
        }
        return $values;
    }

I'm getting this weird syntax error :

Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1 near "show": syntax error (SQL: show columns from defi_user where field = "category";)

Although i copied the query in every syntax checker I know and they all say it's perfectly valid.

What am I missing ? Thanks in advance



via Chebli Mohamed

Is it possible for Laravel 5.5 to configure the sending server for each email separately?

Hellow.

Is it possible for Laravel 5.5 to configure the sending server for each email separately?

I have several clients who each need to send emails from their server.

This is promising. https://laravel.com/api/5.5/Illuminate/Mail/Mailable.html#method___call

But I can't find how to configure the parameters if it's the right place.



via Chebli Mohamed

How to make login for 10 type of users in laravel?

I am making a login for 10 types of users. for Example .. Admin, Cutting Company, Packaging Company, Truck, Boss and more like that. I was thinking about roles and permissions. But I am not sure how I will handle that. Because all type of users has the different king of fields (database columns). And half of the users will be connected through the app. so I will need to create APIs for those users.

So My question is here that I should create 10 Login pages for every type of user? Or I should go for roles and permissions. or Is there any other option is also available.

Is there any package available?



via Chebli Mohamed

How to redirect to customer login page in laravel

I have developed multiauth system with laravel . And I have implemented middleware on routes.

auth is for admin and auth:customer for customer login. i have implemented these middlewares on routes. so now what I want is on customer route if customer is is not logged in it should redirect on customer login but currently it is redirecting on admin login.

customer routes

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

    Route::get('/customer-read-notification', function () {
        Auth::guard('customer')->user()->unreadNotifications->markAsRead();
        return 1;
    });
   });

admin routes

Route::group(['middleware' => ['auth']], function () {
    Route::get('/staff-read-notification', function () {
        Auth::user()->unreadNotifications->markAsRead();
        return 1;
    });
 });


via Chebli Mohamed

vendredi 22 janvier 2021

I am Getting issue of CORS while calling google places api in AJAX laravel 5.4

$.ajax({ type: 'GET', url: 'https://ift.tt/3iLrMOU datainput1 +'&key=apikey

$(document).ready(function () {
            $("#autocomplete_text_1").keyup(function(){
                var datainput = $("#autocomplete_text_1").val();
                $.ajax({
                    type: 'GET',
                    url: 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input='+ datainput +'&key=apikey',
                    dataType: 'json',
                    success:function(data){
                       // console.log(data.predictions);
                        var autocomplete_text_1_from = [];
                        $.each(data.predictions, function(key, value) {
                         //   console.log(value.description);
                            autocomplete_text_1_from.push("<li onclick='getfromride(\""+value.description+"\")'>"+ value.description +"</li>");
                        });
                        $('#autocomplete_text_from_1').html(autocomplete_text_1_from.join(' ').trim());
                    }
                });
            });
            });

', dataType: 'json', success:function(data){ console.log(data); } });



via Chebli Mohamed

Laravel Qr Code Not Working While Sending Email

I am using Laravel version "5.8"

I have installed composer require simplesoftwareio/simple-qrcode - to generate qr code

to generate a Qr code on view i am using this code

 {!! QrCode::size(80)->generate('test data' ); !!}

but when i send the view over a mail , i dont get the Qr code over mail

this is my controller code

        $email = $userInfo['email'];
        $name = $userInfo['fname'];
        $subject = 'Test mail';
        $ccmail = 'test@gmail.com';
        $body = 's';
        Mail::to($email)->send(new Invitationmail($name,$subject,$ccmail,$body,$invitation_id));

View code

  </div>
    <td>{!! QrCode::size(80)->generate('asas' ); !!}</td>
    {!! QrCode::size(200)->generate('W3Adda Laravel Tutorial'); !!}
  <div>

Can some one help me with these ? Thank you



via Chebli Mohamed

How can I search encrypted data in Laravel using like operator

How can I search data in Laravel using like operator, I have used

encrypt($searchValue); 

OR

Crypt::encryptString($searchValue)

But both return full encrypted data but I need searchable data using like operator, In that case, the first name is the encrypted format when is search normal text it returns null


User::where('first_name', 'like', '%' . 'abc' . '%')->get();
//it's return null

When I user

//searchValue is like only 'ab'
User::where('first_name', 'like', '%' . Crypt::encryptString($searchValue) . '%')->get();
//it's also return null 

if anyone has known the solution kindly share the solution



via Chebli Mohamed

I,m trying to update data using ajax. I got my data back but when i try to save in my database it dislpays 500 error

This is My Controller

public function PoststatusChange(Request $request, $Id)
    {
        $value = $request->Id;
        //$tripid = $request->tripid;
        $tripid = $Id;
        $data = SaveReportData::where('tripid', '=', $tripid)->first();
        $datas = SaveReportData::where('Id', '=', $data->Id)->first();
        $f = SaveReportData::find($datas->Id);

        if ($data->Id == $f->Id) {
            $f->paymentstatus = $request->Id;
            $s = $f->paymentstatus;
        }

        $f->save(); //Here Lies an Error When i commented this line i got my response back 


        $string = "";
        if($f->paymentstatus == 1){
            $string = "Your Status Changed to Paid!";
        }
        if($f->paymentstatus == 2){
            $string = "Your Status Changed to Processing";
        }

        return response()->json($string);
    }

This is My Routes

Route::post('statusChange/{Id}','HomeController@PoststatusChange');

Here is My Ajax

function Report() {
        $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        });
        var status = $('#status').val();
        var tripid = $('#tripid').val();
        console.log(status);

        if(status != "" && tripid != ""){
                $.ajax({
                    url: '/statusChange/'+tripid,
                    type: "post",
                    dataType: "json",
                    cache:false,
                    data: {
                        '_token': "",
                        'Id': status,
                        'tripid': tripid,
                    },
                    success: function(response){// What to do if we succeed
                            alert(response);
                        }
                });
            
        }
        
    }

I'm Trying to get id and pass to the controller through ajax i get my response(data) back but when i tried to save the data in database using save() function it gave me 500 error



via Chebli Mohamed

implement EPS/POS in Laravel application

I have one requirement of an eps/pos thermal printer for the invoice printing of item which sold. I do not have any idea how to integrate with laravel application for API and web-based application of laravel.

Anyone can suggest how to do that ??



via Chebli Mohamed

jeudi 21 janvier 2021

In laravel 5.8 is there any method to pass multiple values in api routes of same type in GET method? [closed]

my route api is GET>>http://localhost:8080/public/test/1,2,3,4 how can i pass multiple ID's(1,2,3,4)? in get method like the endpoint above in laravel



via Chebli Mohamed

A non-numeric value encountered with Laravel

I hope you're well. I'm trying to display a message with the search value I've done (I have 3 filed for a search : keyword, article type and date). I have a function inside my Controller :

    public function page_liste_resultat_recherche_article(Request $request)
    { 
      $recherche_effectuer = request()->query('rechercher');
      $type_article_recherche = request()->query('type_article');
      $date_rechercher = request()->query('date');
      $article_rechercher = Article::withTrashed()->when($recherche_effectuer, function($query, $recherche_effectuer){
        return $query->where('titre', 'like', "%{$recherche_effectuer}%");
      })
        ->when($type_article_recherche, function($query, $type_article_recherche){
           return $query->where('type_article_id', 'like', "%{$type_article_recherche}%");
      }) 
        ->when($date_rechercher, function($query, $date_rechercher){
           return $query->where('created_at', 'like', "%{$date_rechercher}%");
      })->orderBy('created_at', 'desc')->paginate(5);

    if((empty($recherche_effectuer)) && (empty($type_article_recherche)) && ($date_rechercher)){
        $message_resultat_recherche = "Résultat pour la date " + ($date_rechercher) + " :";

    } elseif((empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (empty($date_rechercher))){
         $message_resultat_recherche = "Résultat pour le type d'article " + ($type_article_recherche) + " :";

    } elseif((empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (!empty($date_rechercher))){
        $message_resultat_recherche = "Résultat pour la date " + ($date_rechercher) + " et le type d'article " + ($type_article_recherche) + " :";

    } elseif((!empty($recherche_effectuer)) && (empty($type_article_recherche)) && (empty($date_rechercher))){
        $message_resultat_recherche = "Résultat pour le mot cle " + ($recherche_effectuer) + " :";

    } elseif((!empty($recherche_effectuer)) && (empty($type_article_recherche)) && (!empty($date_rechercher))){
        $message_resultat_recherche = "Résultat pour le(s) mot(s) clé(s) " + ($recherche_effectuer) + " et pour la date " + ($date_rechercher) + " :";

    } elseif((!empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (empty($date_rechercher))){
        $message_resultat_recherche =  "Résultat pour le(s) mot(s) clé(s) " + ($recherche_effectuer) + "et le type d'article " + ($type_article_recherche) + " :";

    } elseif((!empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (!empty($date_rechercher))){
        $message_resultat_recherche =  "Résultat pour le(s) mot(s) clé(s) " +($recherche_effectue) + ", le type d'article " + ($type_article_recherche) + " et la date " + ($date_rechercher) + " :";
    } else {
        $message_resultat_recherche = "Vous n'avez saisi aucune donnée";
    }
                
    return view('admin/article/admin_liste_resultat_recherche', [
        'articles' => $article_rechercher,
        'resultat' => $message_resultat_recherche
    ]);
}

Inside my view I show this :

<div class="row d-flex justify-content-center">
  <div class="col-md-12">
     <p class="text-center mt-3"></p>
  </div>
</div>

I've this error :

A non-numeric value encountered

Did someone see where I'm wrong please ?

Cordially



via Chebli Mohamed

Laravel Excel 3.1 - Generate excel without a model

I started to use laravel-excel in my Laravel project.
My problem is that do not use any specific model for the excel I need to generate, so I would like to avoid creating a dummy model class.

I found in the documentation this example:

(new Collection([[1, 2, 3], [1, 2, 3]]))->downloadExcel(
    $filePath,
    $writerType = null,
    $headings = false
)

However there is no more additional information.

In order to read an excel file with no model I found this solution:

$uploadedFiles = $request->file();
$res = Excel::toArray([], $uploadedFiles['file']);

But I do not find the parallel call for exporting.
Any help please?



via Chebli Mohamed

Laravel : ReflectionException Class App\Http\Controllers\DashboardController does not exist

After logging in to my admin dashboard i am getting below error :

ReflectionException Class App\Http\Controllers\DashboardController does not exist

Below is my DashboardController inside : public_html/app/Http/Controllers/Dashboard

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        return view('dashboard.index');
    }
}

Routs file :

Auth::routes();
Route::get('logout', function () {
    \Illuminate\Support\Facades\Auth::logout();

    return redirect('/');
});


Route::get('/', 'HomeController@index')->name('home');
//Route::get('/about', 'AboutController@index')->name('about');
Route::get('/events', 'EventController@index')->name('events');
Route::get('/events/{event}', 'EventController@show')->name('events.show');
Route::get('/publications', 'PublicationController@index')->name('publications');
Route::get('/publications/{publication}', 'PublicationController@show')->name('publications.show');

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

    Route::get('search/', 'SearchController@index')->name('search');

});

Route::middleware(['auth', 'dashboard'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index')->name('dashboard.index');
    Route::resource('/dashboard/users/trashed', 'UserTrashedController', ['as' => 'dashboard.users']);
    Route::resource('/dashboard/users', 'UserController', ['as' => 'dashboard']);
    Route::resource('/dashboard/categories/trashed', 'CategoryTrashedController', ['as' => 'dashboard.categories']);
    Route::resource('/dashboard/categories', 'CategoryController', ['as' => 'dashboard']);
    Route::resource('/dashboard/events', 'Dashboard\EventController', ['as' => 'dashboard']);
    Route::resource('/dashboard/activity-logs', 'ActivityLogController', ['as' => 'dashboard']);
    Route::resource('/dashboard/pages', 'Dashboard\PageController', ['as' => 'dashboard']);
    Route::resource('/dashboard/publications', 'Dashboard\PublicationController', ['as' => 'dashboard']);
});

Route::any('/{any}', '\App\Http\Controllers\PageController@show')->where('any', '.*')->name('pages.show');

Below is my laravel version

Laravel Version: 5.8

i have spent hours on this but unable to find the issue , could someone please help me to fix the issue



via Chebli Mohamed

How to solve "Array to string conversion" in Laravel

I have a Multi-dimensional Array like below

quotation_country_1: ["1", "1", "1"]
quotation_institute_1: ["125", "109", "57"]
quotation_course_1: ["19", "7", "17"]

It has successfully inserted in the database but gives an error for the ajax request "Array to string conversion" So can I get help on how to solve this issue?

public function create_quotation(Request $request)
{
$lead_id = $request->post('selected_lead');

        $data = $request->all();

        if (count($data['quotation_country_1']) > 0) {
            foreach ($data['quotation_country_1'] as $item => $value) {
                $data2 = array(
                    'lead_id' => $lead_id,
                    'interestd_country_id'=>$data['quotation_country_1'][$item],
                    'interestd_institute_id'=>$data['quotation_institute_1'][$item],
                    'interestd_course_id'=>$data['quotation_course_1'][$item],
                );

                DB::table('starter_application_interested_course_ins')
                      ->insert($data2);
            }
        }
}



via Chebli Mohamed

Storing an array of objects in laravel

I have this request

"products":[
        {
           
            "quantity_accepted":15,
            
        },
        {
            
            "quantity_accepted":17,
           
        },
        {
           
            "quantity_accepted":17
        }
    ]

In my controller am trying to iterate and store each object in that array

  foreach($request->get('products') as $product){
                   
          ItemOrder::where('purchase_order_id',$id)
           ->update([
                       
              'quantity_accepted'=>$product['quantity_accepted'],
                        
                       
        ]);
                    
                               
    }

i am only able to store one of the objects which is the last one



via Chebli Mohamed

mercredi 20 janvier 2021

"message":" ", "Symfony\Component\HttpKernel\Exception\NotFoundHttpException" getting error

Laravel Getting Error when ajax requesting Im sending files along with lots of form content with added dynamaticlly

Route::group(['as'=>'employee.', 'prefix' => 'employee', 'namespace'=>'Employee', 'middleware' => ['auth', 'employee']], function(){
Route::post('profile/updateProfile', [App\Http\Controllers\Employee\ProfileController::class, 'updateProfile'])->name('updateProfile'); });

Ajax Request look like

 $.ajax({
            type:'POST',
            url: '',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type: 'POST',   
            contentType: false,
            processData: false,   
            cache: false,        
            data: fm,
            success: function(responce) {
                console.log(responce);            
            },
            error: function(err) {                    
                console.log(err);
            
            },
    });

**Controller For **

public function updateProfile(Request $request)
        {
            dd('IN Profile Controller');
            // return response()->json("Profile Controller");
        }


via Chebli Mohamed

octobercms can't connect to DB; .env is fine and php artisan tinker / echo env('DB_*') outputs correct content

I'm using OctoberCMS and, using the DB settings in the .env file I can connect to the DB without issue and I see a database named "mydatabase". BUT when I do php artisan tinker and do DB::connection()->getPdo(); I get the following:

InvalidArgumentException with message 'Database (mydatabase) does not exist.'

When I do echo env('DB_HOST'); and echo env('DB_PORT'); etc (for DB_DATABASE, DB_USERNAME and DB_PASSWORD) everything looks good. I can connect with those parameters with the mysql CLI command. And yet DB::connection()->getPdo(); is failing.

Any ideas?

I'm running OctoberCMS 1.0.443. tail -f /path/to/myproject/storage/logs/system.log doesn't return anything (despite being writable)



via Chebli Mohamed

MethodNotAllwedException 405 Laraval 5.5.*

I have write some API's routes in api.php file with post method. But when I call this method from postman the laravel application throw following error

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: in file /home/my-repo/public_html/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php on line 255

Route

Route::post('login', 'ApiController@login'); Above route I call from postman with post method but I get error all the time.

Note: I have deployed my code on sharedhosting "namecheap"



via Chebli Mohamed

Class 'Illuminate\Routing\ControllerServiceProvider' not found While Upgrading from Laravel 5.1 to 5.2

I have a Laravel 5.1 install that I am upgrading. I meticulously followed the instructions available at https://laravel.com/docs/5.3/upgrade#upgrade-5.2.0 for the upgrade, including removing Illuminate\Foundation\Providers\ArtisanServiceProvider and Illuminate\Routing\ControllerServiceProvider from the config/app.php file (I am stressing this point, as googling for this issue has suggested this in every response).

Despite this, I am still getting this error when I run composer cache:clear

[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Illuminate\Routing\ControllerServiceProvider' not found error 

and see this error in my browser:

FatalThrowableError in ProviderRepository.php line 146:
Class 'Illuminate\Routing\ControllerServiceProvider' not found

Thinking that perhaps references to these classes were being cached, I checked bootstrap/cache/services.json and removed the references from there as well and then ran composer dump-autoload but I am still getting this error.

I also made sure to copy over example config/app.php from Laravel 5.2 clean install example here: https://raw.githubusercontent.com/ziyed/Laravel-5.2/master/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php

I have read through the similar threads on StackOverflow and Laracast and tried tried to use the advice contained inside, but nothing seems to work.

Any help would be greatly appreciated. For reference, my dev setup is running on a local XAMPP stack under a Windows 10 OS. The other environments are remote, using a traditional LAMP stack with Amazon Linux 2. I was trying to do the upgrade locally.



via Chebli Mohamed

mix vue-template-compiler must be installed as a peer dependency in laravel project

I want to install the latest version of npm in my project, If I run npm install I receive npm WARN Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency but none is installed. You must install peer dependencies yourself. [enter image description here



via Chebli Mohamed

mardi 19 janvier 2021

How to insert pdf page in other pdf file in laravel 5.5

I have one pdf file pdf1.pdf having 30 pages and other pdf file pdf2.pdf having 1 pdf page ,now I want insert second pdf2.pdf in first pdf1.pdf in many places i.e between fifth and sixth page and also between 21 and 22 page .So How can I do it in laravel 5.5



via Chebli Mohamed

I want to covert pdf to text but spatie/pdf-to-text is not working, it is showing error

<?php 
require_once 'vendor/autoload.php';

use Spatie\PdfToText\Pdf;
$path= "C:\xampp\htdocs\ccc\public\ebutifier\pdf";
echo Pdf::getText('simple.pdf', $path);

Error =

The command "sample_1611078320.pdf C:\xampp\htdocs\ccc\public\ebutifier\pdf -" failed. Exit Code: 1(General error) Working directory: C:\xampp\htdocs\ccc\public Output: ================ Error Output: ================ 'sample_1611078320.pdf' is not recognized as an internal or external command, operable program or batch file.

<?php 
require_once 'vendor/autoload.php';

use Spatie\PdfToText\Pdf;
$path= "C:\xampp\htdocs\ccc\public\ebutifier\pdf";
echo Pdf::getText($path, 'simple.pdf');

Error => Could not read sample_1611078773.pdf



via Chebli Mohamed

Route [admin.index] not defined

working with Laravel 5.8 and I have following href link,

href=""

and my web.php route is like this,

Route::get('/admin.index', function () {
    return view('admin.index')->name('admin.index');
});

but I got following error message here Route [admin.index] not defined. (View: F:\2020 technologies\laravel\bestbrandtoday\resources\views\_includes\nav\admin.blade.php)

how could I fix this problem?



via Chebli Mohamed

How can i migrate without artisan command

I want to do migration when during the deployment. I don't have access the ssh for server. What is the best case for this situation? How can i migrate Laravel application on boot.



via Chebli Mohamed

Stored Session in Laravel

I want to stored the addrId only. But I'm having trouble to get that. Below is my array;

"customerInfo" => array:1 [▼
    "accountList" => {#1810 ▼
      +"511000000012015": array:1 [▼
        0 => {#1821 ▼
          +"accountBasicInfo": {#1761 ▶}
          +"contactPersonInfo": {#1817 ▼
            +"contactPersonId": "511000000005007"
            +"addressInfo": {#1818 ▼
              +"addrId": "511000000009029"
              +"addr1": "S"
              +"addr2": []
              +"postalCode": "16390"
            }
          }
        }
      ]
      +"511000000012023": array:1 [▶]

Here is my code. The getResp are calling from API.

/** Initial Response */
$accountList = $addrList = [];

$response['accountList'] = $accountList = $getResp->data;
session()->put('customerInfo.accountList', $accountList);

I'm trying todo like this one, but it wont work. How can I solve it? Currently the addressInfo just return for 511000000012015 but not the next one. I'm stuck to get the session. Please help. Thank you

foreach(session()->get('customerInfo.accountList') as $keys => $addrList) {
    session()->put('customerInfo.addressInfo.addressID', $addrList[0]
    ->contactPersonInfo->addressInfo->addrId);
}


via Chebli Mohamed

Getting PHP Laravel Fatal error: require_once(): Failed opening required

The error that I’m getting is:

Warning: require_once(C:\xampp\htdocs\food/public/index.php): failed to open stream: No such file or directory in C:\xampp\htdocs\food\server.php on line 21 Fatal error: require_once(): Failed opening required 'C:\xampp\htdocs\food/public/index.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\food\server.php on line 21



via Chebli Mohamed

lundi 18 janvier 2021

Laravel upload image using AJAX POST method

I tried to upload an image into the form using ajax method, here the my form code in blade file:

<form action="#" id="form" enctype='multipart/form-data' class="form-horizontal">
        
        <div class="modal-header">
         <h4 class="modal-title">Data Form</h4>
       </div>
       <div class="modal-body"> 
         <div class="form-body">
 
            <div class="form-group">
              <label class="control-label col-md-4">Description</label>
              <div class="col-md-8">
                <input name="description" id="description" class="form-control" type="textarea">
                <small class="errorDescription hidden alert-danger"></small> 
              </div>
            </div> 
            
            <div class="form-group">
              <label class="control-label col-md-4">Price</label>
              <div class="col-md-8">
                <input name="price" id="price" class="form-control" type="number">
                <small class="errorPrice hidden alert-danger"></small> 
              </div>
            </div>

            <div class="form-group"> 
               <input type="file" name="image" id="image">
            </div>      
        </div>
      </div>
    </form>

And the Ajax POST method is:


    function save()
    {   
   
      var url;
      url = "";
      
      $.ajax({
        type: 'POST',
        url: url,
        data: {
          'description': $('#description').val(), 
          'price': $('#price').val(),
          'image': $('#image').val()
        },
        
        success: function(data) { 
        
        console.log(data);
            
             
          }
        }
    }

And here my controller:

  public function store(Request $request){

        // if request has file
        if($request->hasFile('image')){

            $filenameWithExt=$request->file('image')->getClientOriginalName();

            $filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);

            $extension=$request->file('image')->getClientOriginalExtension();

            $fileNameToStore= date('mdYHis') . uniqid() .$filename.'.'.$extension;

            request()->image->move(public_path('img'), $fileNameToStore);  

     }else{
           $fileNameToStore='no-image.jpeg';
      }

  $post = new WhData(); 
  $post->description = $request->description;
  $post->price = $request->price;
  $post->image=$fileNameToStore;
  $post->save();
  return redirect()->back();
  }

But the data never save the uploaded image to the DB, the Database always stored no-image.jpeg (my else condition in controller) for image value. Here my form request in the Header request data in browser console:

description: Watermelon
price: 45
image: C:\fakepath\thumbnail.jpg

Almost 3 days now to solved this and look over the net too, but still no luck. Any idea how to solved this? Thanks,



via Chebli Mohamed

laravel PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist?

laravel-5.2 migration problem?
if I enter php artisan migrate command then return this error pls help me...
problem this line: vendor\laravel\framework\src\Illuminate\Container\Container.php(629) vendor\laravel\framework\src\Illuminate\Foundation\Application.php(697) vendor\laravel\framework\src\Illuminate\Container\Container.php(230) vendor\laravel\framework\src\Illuminate\Container\Container.php(731) vendor\laravel\framework\src\Illuminate\Container\Container.php:734


PS D:\xampp\htdocs\newsflash-2021-01-16> php artisan migrate PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in

D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php:734 Stack trace:

#0 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(734): ReflectionClass->__construct('App\\Exceptions\\...')

#1 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(629): Illuminate\Container\Container->build('App\\Exceptions\\...', Array)

#2 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(697): Illuminate\Container\Container->make('App\\Exceptions\\...', Array)

#3 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(230): Illuminate\Foundation\Application->make('App\\Exceptions\\...', Array)

#4 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(731): Illuminate\Cont in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 734

PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php:734

Stack trace: #0 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(734): ReflectionClass->__construct('App\\Exceptions\\...')

#1 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(629): Illuminate\Container\Container->build('App\\Exceptions\\...', Array)

#2 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(697): Illuminate\Container\Container->make('App\\Exceptions\\...', Array)

#3 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(230): Illuminate\Foundation\Application->make('App\\Exceptions\\...', Array)

#4 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(731): Illuminate\Cont in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 734

via Chebli Mohamed

laravel-8 user table seeder does not exist

I am trying to make a login from laravel 8 but at the begging I faced an error which I cannot find a solution. The UsersTablesSeeder is created but still the compiler cannot find it

   Illuminate\Contracts\Container\BindingResolutionException 

  Target class [UsersTablesSeeder] does not exist.

  at C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:832
    828▕ 
    829▕         try {
    830▕             $reflector = new ReflectionClass($concrete);
    831▕         } catch (ReflectionException $e) {
  ➜ 832▕             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
    833▕         }
    834▕ 
    835▕         // If the type is not instantiable, the developer is attempting to resolve
    836▕         // an abstract type such as an Interface or Abstract Class and there is

  1   C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:830
      ReflectionException::("Class "UsersTablesSeeder" does not exist")

  2   C:\xampp\htdocs\pary\vendor\laravel\framework\src\Illuminate\Container\Container.php:830
      ReflectionClass::__construct("UsersTablesSeeder")

the following code shows DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();
        $this->call(UsersTablesSeeder::class);
    }
}

this is my user table

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\User;

class UsersTablesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name'    => 'John Smith',
            'email'    => 'john_smith@gmail.com',
            'password'   =>  Hash::make('password'),
            'remember_token' =>  str_random(10),
        ]);
    }
}

I am following this link



via Chebli Mohamed

PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist

laravel-5.2 migration problem if I enter php artisan migrate command then return this error pls help me... PS D:\xampp\htdocs\newsflash-2021-01-16> php artisan migrate PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php:734 Stack trace: #0 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(734): ReflectionClass->__construct('App\Exceptions\...') #1 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(629): Illuminate\Container\Container->build('App\Exceptions\...', Array) #2 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(697): Illuminate\Container\Container->make('App\Exceptions\...', Array) #3 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(230): Illuminate\Foundation\Application->make('App\Exceptions\...', Array) #4 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(731): Illuminate\Cont in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 734 PHP Fatal error: Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php:734 Stack trace: #0 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(734): ReflectionClass->__construct('App\Exceptions\...') #1 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(629): Illuminate\Container\Container->build('App\Exceptions\...', Array) #2 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(697): Illuminate\Container\Container->make('App\Exceptions\...', Array) #3 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(230): Illuminate\Foundation\Application->make('App\Exceptions\...', Array) #4 D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php(731): Illuminate\Cont in D:\xampp\htdocs\newsflash-2021-01-16\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 734 PS D:\xampp\htdocs\newsflash-2021-01-16>



via Chebli Mohamed

Server wont serve pages whenever uploading and parsing data Laravel

I have been developing the Biometric Parsing module for my system I have achieved my goal in reading raw data from the biometric unit into the database. My problem is that whenever a user in my system is uploading a raw biometric file the server wont serve any pages or requests while the upload and reading is being processed. I would like to have some pointers and learn some of the principles in handling this process much better

the biometric file that comes from the unit looks like this

  129   2019-06-23 18:13:10 1   0   0   0
   98   2019-06-23 18:51:46 1   0   0   0
  101   2019-06-23 19:07:29 1   1   0   0
  103   2019-06-23 19:07:37 1   1   0   0
   85   2019-06-23 21:14:01 1   1   0   0
  132   2019-06-23 23:48:54 1   1   0   0
  203   2019-06-24 03:45:44 1   0   0   0
  138   2019-06-24 04:10:06 1   0   0   0
  204   2019-06-24 05:12:57 1   0   0   0
  157   2019-06-24 05:58:07 1   0   0   0

the file has more than 1,700+ lines each line is a biometric record

in my Controller have this to evaluate each line and store it in the database a biometric batch is declared in order to keep track of the biometric data being uploaded

public function store(Request $request)
{
    if(Auth::check()){
        $repeatedRecords =0;
        // evaluate if the file is recieved
        set_time_limit(360);
        if($request->hasFile('BiometricDataFile')){
            $biometricDataLogFile = file($request->BiometricDataFile);
            foreach($biometricDataLogFile as $logFile){
                $BiometricDBRecord = new Biometric;
                $biometricRecord = explode("\t", $logFile);
                $BiometricDBRecord->employee_id = $biometricRecord[0];
                $BiometricDBRecord->location = $request->location;
                $BiometricDBRecord->logDate = Carbon::parse($biometricRecord[1]);
                $date = explode(' ', $biometricRecord[1]);
                $BiometricDBRecord->bioDate = $date[0];
                $BiometricDBRecord->bioTime = $date[1];
                $BiometricDBRecord->uploaded_by = Auth::user()->employee_id;
                if(Biometric::where('logDate','=', $biometricRecord[1])->count() <= 0){
                    $BiometricDBRecord->save();
                }else{
                    $repeatedRecords++;
                }
               
            }

            $newBatch = new BiometricBatch();
            //Setting up data for return to view
            $timeNow = Carbon::now('GMT+8')->toDateTimeString();
            $thirtyMinEarlier = Carbon::now('GMT+8')->subHours(12)->toDateTimeString();
            $biometricDataSaved = Biometric::whereBetween('created_at', [$thirtyMinEarlier, $timeNow])->where('uploaded_by', Auth::user()->employee_id)->get();
            $biometricDataSaved->sortBy('logDate');
            $sortedFirst = $biometricDataSaved->first();
            $sortedLast = $biometricDataSaved->last();
            $newBatch->employee_id = Auth::user()->employee->id;
            $newBatch->batch_upload_date = Carbon::now();
            $newBatch->batch_start_date = $sortedFirst->logDate;
            $newBatch->batch_end_date = $sortedLast->logDate;
            $newBatch->isProcessed = false;
            $newBatch->save();
        }else{ //if the file is not recieved
            return "<h1> File not found </h1>";
        }
            $activityLog = new ActivityLog();
            $activityLog->employee_id = Auth::user()->employee_id;
            $activityLog->action = 'Has uploaded biometric data';
            $activityLog->save();
        
        return view('pages.employeeBiometric')->with('savedLogs', $biometricDataSaved, 'duplicates', $repeatedRecords);
    }else{
        return view('errors.401');
    }
       
}

I have a gut feeling that I should probably do this in javascript or ajax but dont know where to start and how to execute.I would like to learn how to implement this better and learn form my mistakes, thank you have a great day.



via Chebli Mohamed

Failed asserting that 200 is identical to 302. in laravel feature testing

I am running test in laravel . But it is failing test. I am not getting the reason may because of middleware but not sure.

Here is test function

public function test_example()
    {
        $staff = factory(Staff::class)->create();
        $response = $this->actingAs($staff) 
        ->withSession(['foo' => 'bar'])
            ->get('/products');

        $response->assertStatus(200);
    }
}

Here is the output

   PHPUnit\TextUI\Command::main()


  Tests:  1 failed, 2 passed
  Time:   0.98s

PS C:\projects\coldxlogistics> php artisan test
Warning: TTY mode is not supported on Windows platform.

   PASS  Tests\Feature\DashboardTest
  ✓ dashboard loads fine
  ✓ user cannot see dashboard without login

   FAIL  Tests\Feature\ProductTest
  ⨯ example

  ---

  • Tests\Feature\ProductTest > example
  Expected status code 200 but received 302.
  Failed asserting that 200 is identical to 302.

  at C:\projects\coldxlogistics\tests\Feature\ProductTest.php:24
     20▕         $response = $this->actingAs($staff)
     21▕         ->withSession(['foo' => 'bar'])
     22▕             ->get('/products');
     23▕
  ➜  24▕         $response->assertStatus(200);
     25▕     }
     26▕ }
     27▕

  1   C:\projects\coldxlogistics\vendor\phpunit\phpunit\phpunit:61
      PHPUnit\TextUI\Command::main()


  Tests:  1 failed, 2 passed
  Time:   1.00s

There are multiple middlwares working on routes. for Example

auth,login_auth,two_factor_auth

and what is the purpose of withSession() how to use it? i see the documentation but can;t understand what is foo, bar



via Chebli Mohamed

Strange problem: in Laravel 5 project in some cases in the url 'index.php' is showing

My client have website build on Laravel 5. It's working fine. My job was to add some features. And it was working fine. But lately strange thing is showing. Sometimes, but not often in the url 'index.php' is showing. Then the website is showing but it's rendering wrong, only html without css and JS. I noticed that when it is showing and I will log into CMS and then logout everything is going back to normal. It's very strange to me and I don't really know why. For example, normal url is look like this: jjk-law.pl/blog, but sometimes it's like this: jjk-law.pl/index.php/blog. I will add my routes code:

Route::get('/administrator', 'SessionsController@index')->name('panel');

Route::get('/administrator/login', 'SessionsController@loginForm')->name('login');

Route::post('/administrator/login', 'SessionsController@login');

Route::get('/administrator/logout', 'SessionsController@logout');

if(env('CMS_INSTALLED') == false) {
    Route::get('/install-cms', 'SiteController@installForm')->name('install');

    Route::post('/install-cms', 'SiteController@installCMS');

    Route::post('/save-env', 'SiteController@saveEnv');
}

Route::get('/', 'SiteController@home')->name('homepage');

Route::get('/index.php', 'SiteController@home');

Route::post('/s', 'SiteController@search');

if(env('CMS_INSTALLED')) {
    $primary_lang_option = Option::where('name', 'primary_lang')->first();

    foreach (Language::where('active', 1)->get() as $lang) {
        App::setLocale($lang->short_name);

        if($primary_lang_option->value != $lang->short_name) {
            Route::get('/'.$lang->short_name.'/'.__('site.register_page'), 'SiteController@registerForm')->name('member_register_'.$lang->short_name);
        } else {
            Route::get('/'.__('site.register_page'), 'SiteController@registerForm')->name('member_register_'.$lang->short_name);
        }
    }

    Route::post('/register', 'SiteController@register');

    foreach (Language::where('active', 1)->get() as $lang) {
        App::setLocale($lang->short_name);

        if($primary_lang_option->value != $lang->short_name) {
            Route::get('/'.$lang->short_name.'/'.__('site.login_page'), 'SiteController@loginForm')->name('member_login_'.$lang->short_name);
        } else {
            Route::get('/'.__('site.login_page'), 'SiteController@loginForm')->name('member_login_'.$lang->short_name);
        }
    }

    Route::post('/login', 'SiteController@login');

    Route::get('/logout', 'SiteController@logout');

    Route::get('/password/reset', 'Auth\ForgotPasswordController@memberResetPasswordForm');

    Route::get('/password/reset/{token}', 'Auth\ResetPasswordController@showMemberResetForm')->name('member.password.reset');

    Route::post('/password/reset/{token}', 'Auth\ResetPasswordController@setNewPassword')->name('member.password.new');
}

Route::post('/send_mail', 'MailerController@send')->name('send_mail');
Route::get('/wiadomosc-wyslana', 'MailerController@success')->name('form-success');

Route::get('/{path}', 'SiteController@showByUrl')->where('path', '.+');

I think that this problem is somehow connected to CMS, have relation with login and logout to CMS, but exactly how I don't know don't know. Anyone have the same problem? Any advice how to fix it? Thanks



via Chebli Mohamed

dimanche 17 janvier 2021

How to use Tag to show children View on top of parent in Laravel blade?

I am new to Laravel and I have been trying to display partial children view on top of parent view using hyperlink. But nothing happens when I click on my hyperlink. on the other hand it is working on normal button.

Here is the code that works without any problem on normal button.

  <button type="button" id="close_register" title="" class='button-custom' data-container=".close_register_modal" 
      data-href="">
        <!-- <strong><i class="fa fa-window-close fa-lg"></i></strong> -->
  </button>

And here is the hyperlink based button code.

<a id="close_register" data-container=".close_register_modal" 
data-href="" class='glowBtn'>Day Close
</a>

Any help would be highly appreciated Thanks in advance.



via Chebli Mohamed

samedi 16 janvier 2021

Show Products From specific category in Laravel

I just want to show product with "Rumored" table can someone help how can I show them in my side bar? below is my sidebar code. And side bar Already show 12 Latest Products from all categories it must show only 8 product and with "Rumored" category. not from all categories.

<div class="heading mb-2">
    <h3>Rumored Phones</h3>
</div>

<div class="row">
    @foreach ($popular_devices as $device)
    <div class="col-xl-3 col-lg-4 col-md-6 col-sm-6 col-6">
        <div class="device-box">
            @if($device->image)
            <a title=" " href="">
                <img src="" alt="" class="img-fluid"></a>
            @endif
            <a class="title" title="" href=""></a>
        </div>
    </div>
    @endforeach
</div>

<div class="text-center mb-4">
    <a class="btn btn-light btn-block" href="" title="All devices">View All  Devices</a>
</div>

enter image description here



via Chebli Mohamed

vendredi 15 janvier 2021

Laravel database connections being kept open

I have this Laravel app that keeps 50 ish processes running sleep command and every time I kill those they keep coming back.

I have no idea where to look first and how to resolve this issue. I simply don't want this many connections being open on the server.

I tried to delete all failed_jobs from the table, there are no jobs to attempt.

The laravel scheduler runs every minute to make the queue work in order to send the mails.

enter image description here



via Chebli Mohamed

jeudi 14 janvier 2021

Laravel accessing image in Storage folder on WAMP

Laravel accessing image in Storage folder is working on live server but it is not working on the local server (below is the error)

enter image description here



via Chebli Mohamed

I'm getting Laravel Exception

I'm working on a project and I'm using dompdf to create and render PDF.

"No block-level parent found. Not good"

I'm getting this error. Screenshot also attched

In development it works fine. But when i create PDF i got strange error.

Any idea what is the reason behind this? and how to fix?



via Chebli Mohamed

Laravel Parse Data By ID Foreach Loop From Different Table

so I would like to get each data from two different table and display in on my view according to the ID of each row on the view table. However, I am stuck as I was not able to display the data according to their ID and now it is showing all my rows from the other two tables as follow:

enter image description here

Table Event

Table Event_Details

Table Event_Participants

Here is my table section within the view:

<table class="table table-hover table-borderless">
        <tr>
            <th class="text-center" width="10px">No</th>
            <th width="250px">Event Name & Venue</th>
            <th width="120px">Event Start</th>
            <th width="120px">Event End</th>
            <th width="80px" class="text-center">Category</th>
            <th width="80px">Participant</th>
        </tr>
        @foreach ($events as $event)
            <tr>
                <td class="text-center"></td>
                <td> <br/>
                 
                    Venue: 
                    @foreach ($event_details as $event_detail)
                    
                    @endforeach
                 
                
                
                </td>
                <td> </br>  </td>
                <td> </br> </td>
                <td class="text-center">
                    @switch($event->event_category)
                    @case($event->event_category==1)
                        HQ-Based
                        @break
                        @case($event->event_category==2)
                        Stakeholder
                        @break
                        @case($event->event_category==3)
                        Webinar
                        @break
                        @case($event->event_category==4)
                        Online Training
                        @break
                    @default
                @endswitch    
                
                </td>
                <td class="text-center">
                 
                    <ol>
                        @foreach ($event_participants as $parti)

                            <li>
                                
                    
                         
                             @foreach ($users->where('id', $parti->user_id) as $user)
                                 
                             @endforeach
                         
                         </li>
                       
                        
                        @endforeach
                     </ol>

                </td>
            </tr>

        @endforeach
    </table>

Here is my controller:

  public function filter(Request $request)
    {

        $events = Event::where([
            ['id', '!=', Null],
            [function ($query) use ($request) {
                // if (($search = $request->search)){
                //     $query->orWhere('event_parts' , 'LIKE', '%' . $search . '%') ->get();
                // }

                if (($search = $request->search AND $searchdate1 = $request->DateFilter1 AND $searchdate2 = $request->DateFilter2)) {
                    $query->orWhere('event_parts' , 'LIKE', '%' . $search . '%');
                    $query->whereBetween('event_start',[$searchdate1,$searchdate2]) ->get();

                }
                if (($searchdate1 = $request->DateFilter1 AND $searchdate2 = $request->DateFilter2)) {
                    $query->whereBetween('event_start',[$searchdate1,$searchdate2]) ->get();

                }
                if (($searchdate1 = $request->DateFilter1)) {
                    $query->whereBetween('event_start',[$searchdate1,now()]) ->get();
                }

            }]

        ])
           ->paginate(1000);
        $events = Event::paginate(5);

        $officers = User::all();

        // return view('events.filter', compact('events' , 'officers', 'officers2'))
        //     ->with('i', (request()->input('page', 1) - 1) * 10);
        return view('events.filter', compact('officers'));
    }

    public function print(Request $request)
    {

        $events = Event::where([
            ['id', '!=', Null],
            [function ($query) use ($request) {
      
                if (($search = $request->search AND $searchdate1 = $request->DateFilter1 AND $searchdate2 = $request->DateFilter2)) {
                    $query->orWhere('event_parts' , 'LIKE', '%' . $search . '%');
                    $query->whereBetween('event_start',[$searchdate1,$searchdate2]) ->get();

                }
                if (($searchdate1 = $request->DateFilter1 AND $searchdate2 = $request->DateFilter2)) {
                    $query->whereBetween('event_start',[$searchdate1,$searchdate2]) ->get();

                }
                if (($searchdate1 = $request->DateFilter1)) {
                    $query->whereBetween('event_start',[$searchdate1,now()]) ->get();
                }

            }]

        ])
            ->paginate(1000);


            $events = Event::all();
            $users = User::all();
        
            $event_id = DB::table('events')->pluck('id');
            $event_details = Event_Details::all();
            
            // $event_details = Event::with('event_venue')->where('id', $event_id)->get();
      
    
            $event_participants = DB::table('event_participants')
            ->join('events' ,'event_participants.user_id', '=','events.id')
       
            ->get();
    
        
           
        return view('events.print', compact('events', 'users', 'event_participants', 'event_details'))
            ->with('i', (request()->input('page', 1) - 1) * 10);

    }
}

Model Events:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    protected $fillable = [
        'event_name',
        'event_category',
        'event_start_date',
        'event_end_date',
    ];

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

    public function participants()
    {
        return $this->hasMany('App\Event_Participants', 'event_id');
    }

 
    public function details()
    {
        return $this->hasOne('App\Event_Details', 'event_id');
    }
}

Model Event_Participants:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event_Participants extends Model
{
    
    protected $table = 'event_participants';

    protected $fillable = 
    [
        'event_id',
        'user_id',
    ];

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

Model Event_Details:

   <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Event_Details extends Model
    {
    
        protected $table = 'event_details';
    
        protected $fillable = [
        'event_id',
        'event_venue',
        'event_desc',
        'event_rem',
        'event_start_time',
        'event_end_time',
        'event_adder',
        ];
    
        public function events()
        {
            return $this->belongsTo('App\Event' ,'event_id');
        }
    }


via Chebli Mohamed