vendredi 31 mai 2019

How to convert select statement to eloquent?

This works in existing website, trying to convert to laravel 5.8

SELECT DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at, '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total' FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC");

I tried:$archives = DB::select("SELECT DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at, '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total' FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC");

Error: SQLSTATE[42000]: Syntax error or access violation: 1055 'amohdb.posts.created_at' isn't in GROUP BY (SQL: SELECT DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at, '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total' FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC)



via Chebli Mohamed

Remove index.php from URL in laravel 5.0 in hostgator shared hosting

I am using hostgator shared hosting. In that I created one laravel project. While running without index.php the URL is not working. But I want to remove index.php from URL. My .htaccess file is,

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

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

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

Is this issue because of hostgator shared hosting or htaccess file? Please help me.



via Chebli Mohamed

Created a fresh database, now running any artisan command throws an error about a missing table

I wanted a fresh development database so I could seed with new data, so I manually dropped and recreated my development database and now running any artisan commands throws an error. I continuously get an error saying that I'm missing a table.

In Connection.php line 647:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'   
  doesn't exist (SQL: select * from `stores`)                                   


In PDOConnection.php line 63:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'   
  doesn't exist                                                                


In PDOConnection.php line 61:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'   
  doesn't exist                                                                

I haven't run php artisan migrate:refresh in a long time so I'm not sure where the table stores is being used that's causing this error. Adding a -v flag doesn't provide any additional output to further trace the stack.

I've tried manually dropping the database and recreating it via the mysql. I've tried composer dump-autoload but that doesn't help either. I can't run php artisan migrate:install because calling ANY artisan command will throw the same error. Even calling php artisan throws the error. I've tried looking at my service providers to see if the table is being referenced in any of the constructors but I don't see it being used.

Is there anywhere in the code I should be checking for the use of this table? I'm not sure what is instantiated when php artisan is called.

The stores table is actually my first migration, so it's supposed to be the first thing created, but for some reason it's being called as a part of the artisan process.



via Chebli Mohamed

Check checked checkbox in Laravel

I have this code:

$arrayWithSelectedValues = [[user_id] => 3,[language_id] => 2], [user_id] => 3,[language_id] => 12]]

And I have checkbox :

@foreach($languages as $language)
<fieldset>
<input type="checkbox"
   class="icheckbox_square-red"
   id="input-15" name="languages[]"
   value="">
<label for="input-15"></label>
</fieldset>
@endforeach

How can I mark checkboxes as marked - those that have language_id from the array = $ language-> id?



via Chebli Mohamed

Trying to get property 'account_status' of non-object

I am getting an error Trying to get property 'account_status' of non-object. How will i fixed it. Actually I was trying to do that if account_status == 1 then i can able to login otherwise not.

public function login(Request $request){ 
        $account_status=Auth::user()->account_status;
        if($account_status == 1){
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password')])){
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } }
    }

please help me out to solve this problem. I will be very grateful to you Thank you



via Chebli Mohamed

How to fetch all from table1 and attach count of rows from table2 in a single query by laravel eloquent

I'm using Laravel 5.8, and I have 2 tables in a (one-to-many) relationship as below:

Contacts DB

  • id
  • name
  • number

Send DB

  • id
  • user_id
  • text
  • to
  • time

what I want to achieve is a list of all (Contacts) along with how many (send) they've made that related to that (contact) by matching Contacts.id with Send.user_id,

here is the result of the query that I'm looking for:

Query result:

  • id
  • name
  • number
  • count of Sends

Thank you :)



via Chebli Mohamed

Laravel Voyager - upload image on front-end with custom form

I'm working with the voyager (Laravel). I have a model with an image field, this model was created in the backoffice and I already have CRUD for it. I wanted to create a form in the frontend so there could be submited of unlogged users. But I do not know how to upload to follow the same rules that the voyager uses in the backoffice (automatically generated CRUD)

Any help? Thank u



via Chebli Mohamed

How get properties from object in Laravel

I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}

How can I get latitude and longitude from this object?



via Chebli Mohamed

Why does Laravel login attempt redirects back to the login page?

Laravel redirect me back to the login page after each attempt to login. How do i fix this issue?

I've tried changing the session from 'file' to 'database' and clearing all the cache(both in the browser and in laravel, yet it's still redirects back to the login page)

Here is the web route:

 // Login
 Route::post("/profile/dashboard","LoginController@login")->name('login');

Here is my controller:

    public function login(Request $req)
    {
        // validate form
       $req->validate([
            "email" => "required|email|max:255",
            "password" => "required|max:16",
        ]);

        $user = ["email" => $req->email, "password" => $req->password];

        // Attempt to login
        if (!Auth::attempt($user)) {

            return back();

        }
        // Redirects to dashboard
        return redirect()->route('dashboard');
    }

Sorry for the poor formatting. Here is my view:

   <form action="" 
        method="post" class="user">
        
        <div class="form-group">
          <input type="email" name="email" id="email" class="form-control 
          form-control-user" aria-describedby="emailHelp"   placeholder="Enter Email Address...">
                          <label class="error" for="email">
                            @include("pages.errors.email")
                          </label>
                        </div>
                        <div class="form-group">
                          <input type="password" name="password" id="password" class="form-control form-control-user" placeholder="Password">
                          <label class="error" for="password">
                            <label class="error" for="password">
                              @include("pages.errors.password")
                            </label>
                          </label>
                        </div>
                        <div class="form-group">
                          <div class="custom-control custom-checkbox small">
                            <input type="checkbox" class="custom-control-input" id="customCheck">
                            <label class="custom-control-label form-check-label" for="customCheck">Remember Me</label>
                          </div>
                        </div>
                        <button type="submit" class="btn btn-outline-success btn-user btn-block text-uppercase">Login</button>
                        <hr>
    <a href="index.html" class="btn  btn-danger btn-google 
     btn-user btn-  block text-uppercase">
                          <i class="fab fa-google"></i> Login with Google
                        </a>
  </form>

I dont't if this will help but here is my session set to database:

   'driver' => env('SESSION_DRIVER', 'database'),

No Error was generate. It redirects back to the login page without any given error.



via Chebli Mohamed

How will I set if account_status = 1 then I can able to login otherwise not able to login?

How will I set if account_status = 1 then I can able to login otherwise not able to login? email, phone and password must be there. This is the following code

public function login(Request $request){ 

        if(Auth::attempt(['email' => request('email'), 'password' => request('password'),
        'account_status'=> request('account_status')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }

Please help me out to solve this problem i'll be grateful to you



via Chebli Mohamed

Laravel Queue Job gives error Model not found

I have created the job file and I'm dispatching the mail through the controller using mailable it will create the entry in job table but after the few seconds it will transfer the record into the failed_jobs table and gives error model not found

Controller Dispatch method

if (!empty($emails) && isset($result->email)) {
                dispatch(new SendNotificationEmailJob($emails, $result, 'WarehouseAddUpdate', array($subject, $request['number'], 'add')));
        }

SendNotificationEmailJob Class

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;

class SendNotificationEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $emails;
    protected $result;
    protected $mailClass;
    protected $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($emails, $result, $mailClass, $data)
    {   
        $this->emails = $emails;
        $this->result = $result;
        $this->mailClass = 'App\Mail\\'.$mailClass;
        $this->data = $data;        
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {           
        if ($this->result == null) {
            if (!empty($this->emails)) {            
                $to = $this->emails[0];    
                unset($this->emails[0]);
            }
        }else{
            if($this->result != null && isset($this->result->email)){                
                $to = $this->result->email;
                if (($key = array_search($this->result->email, $this->emails)) !== false) {
                    unset($this->emails[$key]);
                }            
            }
        }

        if (!empty($this->emails) && isset($result->email)) { 
            $email = new $this->mailClass($this->data);           
            Mail::to($to)->cc($this->emails)->send($email);            
        }

        if (empty($emails) && isset($result->email)) {
            $email = new $this->mailClass($this->data);
            Mail::to($to)->send($email);
        }        
    }
}

Mailable Class

<?php

namespace App\Mail;

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

class WarehouseAddUpdate extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * The data object instance.
     *
     * @var data
     */
    public $subject;

    public $warehouse;

    public $type;

    public $oldstatus;

    public $newstatus;

    public $receiver;


    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->subject = $data[0];
        $this->warehouse = $data[1];
        $this->type = $data[2];
        $this->oldstatus = $data[3] ?? null;
        $this->newstatus = $data[4] ?? null;
        $this->receiver = 'Manager';
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('mails.warehouseaddupdate')->subject($this->subject);
    }
}

The error I found in DB failed_jobs table

Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Model\V1\User]. in /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:416 Stack trace:

0 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php(54):

Illuminate\Database\Eloquent\Builder->firstOrFail()

1 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/SerializesModels.php(41):

App\Jobs\SendNotificationEmailJob->getRestoredPropertyValue(Object(Illuminate\Contracts\Database\ModelIdentifier))

2 [internal function]: App\Jobs\SendNotificationEmailJob->__wakeup()

3 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(42):

unserialize('O:33:"App\Jobs\...')

4 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(76):

Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)

5 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(320):

Illuminate\Queue\Jobs\Job->fire()

6 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(270):

Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))

7 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(114):

Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))

8 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(101):

Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))

9 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(85):

Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')

10 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()

11 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29):

call_user_func_array(Array, Array)

12 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87):

Illuminate\Container\BoundMethod::Illuminate\Container{closure}()

13 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31):

Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))

14 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Container/Container.php(549):

Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)

15 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Console/Command.php(183):

Illuminate\Container\Container->call(Array)

16 /var/www/html/smartcgd/vendor/symfony/console/Command/Command.php(252):

Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))

17 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Console/Command.php(170):

Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))

18 /var/www/html/smartcgd/vendor/symfony/console/Application.php(946):

Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

19 /var/www/html/smartcgd/vendor/symfony/console/Application.php(248):

Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

20 /var/www/html/smartcgd/vendor/symfony/console/Application.php(148):

Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

21 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Console/Application.php(88):

Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

22 /var/www/html/smartcgd/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(121):

Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

23 /var/www/html/smartcgd/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput),

Object(Symfony\Component\Console\Output\ConsoleOutput))

24 {main}



via Chebli Mohamed

how to fix duplicate entry error in Laravel 5.7?

I am using a user verification system in email with Laravel 5.7 this is working fine. but when I tried to enter the same email with verification form it is generating following massages. SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mymail@gmail.com' for key 'users_email_unique' (SQL: insert intousers(email,name,address,updated_at,created_at) values (mymail@gmail.com, Banda, Sysney, 2019-05-31 11:32:36, 2019-05-31 11:32:36))

my UserController is like this,

rotected function store(Request $request)
    {

        $user = new User;

        $user->email = $request->input('email');
        $user->name = $request->input('name');
        $user->address = $request->input('address');

        $user->save();

        $verifyUser = VerifyUser::create([
            'user_id' => $user->id,
            'token' => str_random(40)
        ]);

how can fix this problem?



via Chebli Mohamed

How to open pdf from ajax response

I am trying to open a PDF document received as a response text, in a new browser tab.

My controller code is :

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord,'HTML');
$objWriter->save('helloWorld.html');
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('helloWorld.html');
$data = $pdf->stream();
return $data;

And the ajax code so far (not working) :

$('body').on('click', '.printInvoice', function () {
    var purchase_id = $(this).data("id");
        $.ajax({
            type: "GET",
            url: "/purchases/print" + '/' + purchase_id,
            success: function (data) {
                console.log(data);
                var blob = data;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = "PdfName-" + new Date().getTime() + ".pdf";
                document.body.appendChild(link);
                link.click();
            },
            error: function (data) {
                var data2 = JSON.parse(data.responseText);
                alert(data2['errors']);
            }
        });
});

The code above is generating following error : 'createObjectURL' on 'URL': No function was found that matched the signature provided.

Please help to fix above code, or give a better solution to the problem.



via Chebli Mohamed

ics file : event not added to organizer's calendar

I am using a library that helps me to generate an ics file on laravel. I had to modify it a little bit so it works on outlook (problem with the dates & the time zones). Here's the code for the generation :

class Ics implements Generator
{
public function generate(Link $link): string
{
    $url = [
        'BEGIN:VCALENDAR',
        'PRODID:-//Google Inc//Google Calendar 70.9054//EN',
        'VERSION:2.0',
        'CALSCALE:GREGORIAN',
        'METHOD:REQUEST',
        'X-WR-TIMEZONE:Europe/Paris',
        'BEGIN:VEVENT',
    ];


    $dateTimeFormat = "Ymd\THis\Z";
    $url[] = 'DTSTART:'.gmdate($dateTimeFormat,strtotime($link->from->format('Y-m-d H:i')));
    $url[] = 'DTEND:'.gmdate($dateTimeFormat,strtotime($link->to->format('Y-m-d H:i')));
    $url[] = 'DTSTAMP:'.date('Ymd\THis');

    if ($link->organizer) {
        $url[] = 'ORGANIZER;CN=' . $this->escapeString($link->organizer) . ':mailto:' . $this->escapeString($link->organizer);
        $url[] = 'ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE;CN=' . $this->escapeString($link->organizer) . ';X-NUM-GUESTS=0:mailto:' . $this->escapeString($link->organizer);
    }
    $url[] = 'UID:'.$this->generateEventUid($link);
    if ($link->attendee) {

        foreach ($link->attendee as $attendee) {
            $url[] = 'ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=' . $this->escapeString($attendee) . ';X-NUM-GUESTS=0:mailto:' . $this->escapeString($attendee);
        }
    }
    if ($link->description) {
        $url[] = 'DESCRIPTION:'.$this->escapeString($link->description);
    }
    if ($link->address) {
        $url[] = 'LOCATION:'.$this->escapeString($link->address);
    }
    $url[] = 'SEQUENCE:0';
    $url[] = 'STATUS:CONFIRMED';
    $url[] = 'SUMMARY:'.$link->title;
    $url[] = 'TRANSP:OPAQUE';
    $url[] = 'END:VEVENT';
    $url[] = 'END:VCALENDAR';
    $redirectLink = implode('%0d%0a', $url);

    return 'data:text/calendar;charset=utf8,'.$redirectLink;
}

}

When I create my event, a mail is sent to all attendees (except the organizer) with the ics file atteched. With Gmail and Outlook, it makes the little confirmation box appear, and when I confirm with outlook, it even sends a confirmation mail to the organizer (not with Gmail, but I'm working on it).

The problem is that the event is added to the attendees' calendars, but not the organizer's. I found a post from '14 on SO saying that I should change METHOD from REQUEST to PUBLISH, but it makes outlook not recognize the ics file.

Does anyone have an idea? Thanks a lot.



via Chebli Mohamed

Laravel postcode lookups

I'm trying to add an address lookup to a few forms, where the user can enter a UK postcode and house number and then the other address lines are auto-filled.

I've turned up one or two potentially promising things on Github but they're pretty old and lack really clear, dumbed-down instructions (I'm a Laravel / MVC / OOPHP noob so really need it spelled out).

I'd be open to something API-based that connects to a paid or free service, or alternatively I'm not opposed to downloading the postcode database to host locally if that's better.

If it's something anyone has done with Laravel recently, I'd really appreciate some guidance.



via Chebli Mohamed

How will I set condition that only role 1 and role 2 can register; role 3 and role 4 are failed to register in Laravel:

Please any One help me out to solve the problem. I really stuck into this logic I don't even understand how to implement such kind of Logic.

This is my following code.

Role Table

id role_name
1  Admin
1  Driver
3  Customer
4  Employee

This is my Registration function

public function store(Request $request)
    {
        //
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'phone' => 'required',
            'role_id'=>'required',
            'email' => 'required|email', 
            'password' => 'required',
            'c_password' => 'required|same:password'            
        ]);
        if ($validator->fails()) { 
                return response()->json(['error'=>$validator->errors()], 401);            
            }
        $input = $request->all(); 
        $input['password'] = bcrypt($input['password']); 

        $image = $request->file('photo');
        $new_name = '/images/'.'_'.date('d-m-Y-H-i-s') . '.' . $image->getClientOriginalName();
        // $new_name = '/images/'.$image.'_'.date('d-m-Y-H-i-s');
        $image->move(public_path('images'), $new_name);
        $input['photo']=$new_name;
        $input['created_by']=Auth::user()->id;
        $input['updated_by']=Auth::user()->id;
        $user = User::create($input); 
        $success['token'] =  $user->createToken('MyApp')-> accessToken; 
        $success['name'] =  $user->name;
        return response()->json(['success'=>$success], $this-> successStatus);


    }

Can anyone please help me out to solve this problem? I don't have any idea how will i do this



via Chebli Mohamed

How desplay the number from the Code in blade Laravel

Show only the variable number in the blade from the $sum value

    $sum = OrderPosition::select(DB::raw('sum(quantity*product_price) AS total_sales'))->where('quantity', '<>', 1)->get();

the output is {"total_sales":"550.00"}



via Chebli Mohamed

How will I Convert the following sql query to laravel

SELECT * FROM `users` WHERE (email=$email or phone=$phone) AND is_deleted=0 AND role_id!=2 AND role_id!=3

Please help me out to solve this problem?



via Chebli Mohamed

jeudi 30 mai 2019

Laravel Datatable ManyToMany relationship with multiple tables

Offer.php #model

use App\OfferCategory;
use App\OfferCountries;
use App\OfferCreative;
use App\OfferTools;
use App\OfferTraffic;

class Offer extends Model {
public function offer_countries() {
    return $this->belongsToMany(OfferCountries::class);
}

public function offer_categories() {
    return $this->belongsToMany(OfferCategory::class);
}

public function offer_creatives() {
    return $this->hasMany(OfferCreative::class);
}

public function offer_tools() {
    return $this->hasMany(OfferTools::class);
}

public function offer_traffic() {
    return $this->hasMany(OfferTraffic::class);
}

public function platforms() {
    return $this->hasMany(Platform::class);
}

}

OfferController.php

 public function getMediaData() {
//        $model = Offer::with('offer_traffic');
//        return DataTables::eloquent($model)
//                        ->addColumn('traffic', function (Offer $user) {
//                            return $user->offer_traffic->map(function($post) {
//                                        return str_limit($post->allowed_traffic, 30, '...');
//                                    })->implode('<br>');
//                        })
//                        ->toJson();

        return datatables(DB::table('offers'))->toJson();
    }

I want to use all relation table given in offer.php and image in data table. I have tried with commented code in the controller but not able to get please help me to know where I'm doing wrong.

OfferCountries.php #model

use App\Offer;

class OfferCountries extends Model {

   function offers() {
         return $this->belongsToMany(Offer::class);
    }
}

 Database schema



via Chebli Mohamed

how to store the primarkey values to the foreign key at same time of save

i am new to the laravel and trying to store the primarykey values of patientid to the foreign key of patient_id in address table

$patdet = $request->patdet; foreach($patdet as $patdets) {

    $pdet = new Patient();

    $pdet->fname = $patdets['fname'];
    $pdet->mname =  $patdets['mname'];
    $pdet->lname =  $patdets['lname'];
    $pdet->age   =  $patdets['age'];
    $pdet->blood_group = $patdets['bloodgroup'];
    $pdet->gender  = $patdets['gender'];
    $ptid = $pdet->save();
   }

$addr = $request->address[0];

                $address=new Address;

                $address->gps_lat = $addr['gps_lat'];
                $address->gps_log = $addr['gps_long'];
                $address->house_no  = $addr['houseno'];
                $address->zipcode    =  $addr['zip_code'];
                $address->street    = $addr['street'];
                $address->chowk  = $addr['chowk'];
                $address->city   = $addr['city'];
                $address->patient_id = $patid->id;
                $address->save();

i know that $ptid is local variable and cannot be used in address table ? so how can i store it in address table ??



via Chebli Mohamed

Receive data from mobile

I'm using laravel to implement rest api. My Api server provides data/resources some transactions are processed in mobile. I need those transactions are synced with my web server. My problem is how can receive the mobile transactions data. Normally i used postman for handling api. In this situation how can i receive the data from source is, some other endpoint.



via Chebli Mohamed

laravel request not redirect right page

i want to make a filter based on request 'kelas' on database table. it give me no error just when i click one of the filter it don't show jadwal page with my filter, it show the main page but the url is right like lps.com/?jadwal-2

i have done make a middleware called SanitizeMiddleware from Laravel $request->has('name') doesn't work but still not worked

this is my route web

Route::get('/', 'HomepageController@index');

Route::resource('pengumuman', 'PengumumanController');
Route::resource('jadwal', 'JadwalController');
Route::resource('rapot', 'RapotController');

this is my index() from my jadwalController

public function index()
    {
        if (request()->has('kelas')) {
            $jadwal = jadwal::where('kelas', request('kelas')); 
            }
            else{
            $jadwal = jadwal::all();
            }
            return view('jadwal.index')->with('jadwal',$jadwal);

        //$jadwal = jadwal::all();
        //return view('jadwal.index')->with('jadwal',$jadwal);
    }

this is my index blade

<div class="container">
    <br>
      <h1><strong>Jadwal Pelajaran</strong></h1>
    <a href="/?kelas=1">jadwwal kelas 1</a>
    <a href="/?kelas-2">jadwal kelas 2</a>
    <a href="/?kelas-3">jadwal kelas 3</a>
    </form>
    <table class="table table-bordered">
      <thead>
        <tr>
          <th scope="col"></th>
          <th scope="col">07.00-08.00</th>
          <th scope="col">08.00-09.00</th>
          <th scope="col">09.00-10.00</th>
          <th scope="col">10.00-11.00</th>
          <th scope="col">10.00-12.00</th>
          <th scope="col">action</th>
        </tr>
      </thead>
      <tbody>
      @if(count($jadwal)>0)
      @foreach($jadwal as $jadwals)
        <tr>
        <th scope="row"></th>
        <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        <td><a href="/jadwal//edit" class="btn btn-info">Edit</a></td>
        </tr>
        @endforeach
        @else
        <p>tidak ada jadwal</p>
        @endif
      </tbody>
    </table>



</div>

and this is the picture of problem this is my jadwal page before filter

this my page after i click the filter using request()



via Chebli Mohamed

Why Laravel gives me this inexisten error?

I get this error "Trying to get property 'idperiod' of non-object", in the exeption tells me it's at line 46 and there is no idperiod anywhere, the thing is that I don't have that variable by now, I erased and change it for anotherone, but Laravel keep giving me the error, wath could I do to fix this.

I had clean the browser history, and try to clean artisan cache but yet I still get the error.



via Chebli Mohamed

Laravel blank projects.. so many files! Can it be reduced somehow?

Last time I used Laravel was a long time ago and I decided to get back to it.

Now coming from CodeIgniter, which was a powerful framework in its own time, I was happy to upload projects to websites as the "system" folder containing the framework files contained only 121 files.

The problem with composer-based solutions however is that a tiny project can become huge, much bigger than a very large scale CodeIgniter project back in the days. All the dependencies have test folders, documentation, and tons of modules when sometimes only one method is used.

I gasped when creating an empty Laravel project using the instructions from the official documentation and seeing the "vendor" folder containing over 8,000 files!! (Not counting the folders) And it's doing nothing yet.. That is when using the --prefer-dist flag by the way.

So my question is if there is a way to have a more selective empty Laravel project, as servers often have limited Inodes and 8,000 files + folders for every project makes you reach the limit really quickly (and upload takes forever if you can't install composer on your server).



via Chebli Mohamed

Why isn't my listner attached to my event?

Im trying to call an event within my controller.That event should reach for a listener. The listener should send an email. But the listener never gets reached. Telescope says that my event doesn't have a listner. Why is there no listner attached to my event?

Controller:

namespace App\Http\Controllers;

use App\Match;
use App\Tournament;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Events\ToernooiMail as ToernooiMailEvent;

class TournamentController extends Controller
{
 public function store()
 {

    $toernooi = Tournament::create(request([
        'name' => 'name',
    ]));

    event(new ToernooiMailEvent($toernooi));

    return redirect('tournaments');
 }

The event thats reached for:

<?php

namespace App\Events;

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

class ToernooiMail
{
 use Dispatchable, InteractsWithSockets, SerializesModels;

 public $toernooi;

 /**
  * Create a new event instance.
  *
  * @return void
  */
 public function __construct($toernooi)
 {
     $this->toernooi = $toernooi;
 }

 /**
  * Get the channels the event should broadcast on.
  *
  * @return \Illuminate\Broadcasting\Channel|array
  */
 public function broadcastOn()
 {
     return new PrivateChannel('channel-name');
 }
}

The listner that isn't reached:

 <?php

 namespace App\Listeners;

 use App\Events\ToernooiMail;
 use Illuminate\Queue\InteractsWithQueue;
 use Illuminate\Contracts\Queue\ShouldQueue;
 use App\Mail\toernooiMail as toernooiEmail;


class SendToernooiMail
{
/**
 * Create the event listener.
 *
 * @return void
 */
public function __construct()
{

}

/**
 * Handle the event.
 *
 * @param  ToernooiMail  $event
 * @return void
 */
public function handle(ToernooiMail $event)
{
    \Mail::to('dannylenoir@gmail.com')->send(
        new toernooiEmail($event->toernooi)  
    );
}
}

The eventServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as        ServiceProvider;
use App\Events\ToerooiMail;
use App\Listeners\SendToernooiMail;

class EventServiceProvider extends ServiceProvider
{
  /**
   * The event listener mappings for the application.
   *
   * @var array
   */
  protected $listen = [
      Registered::class => [
        SendEmailVerificationNotification::class,
      ],

    ToerooiMail::class => [
        SendToernooiMail::class,
    ],
 ];

  /**
   * Register any events for your application.
   *
   * @return void
   */
 public function boot() 
      parent::boot();

        //
    }

}

My event is called, but it doens't reach the email in my listener. In telescope it says that my event doesn't have a listener.



via Chebli Mohamed

How to post data in my testcase to controller

I am new to php and I am currently trying to make a testcase for an add function I wrote for adding records in the table "project_point" of my database. In this testcase I want to post some test data to that add function and check if the data is set correctly.

Project Point Add function

public function addProjectPoint (Request $request) {
    $point = new ProjectPoint();

    $location = new Point($request->markerLat, $request->markerLong);

    $point->project_id = $request->project_id;
    $point->location = $location;
    $point->area = $request->area;
    $point->name = $request->name;
    $point->information = $request->information;
    $point->category = $request->category;

    $point->save();
}

My test case

public function testCreateProjectPoint()
    {
        $this->post('admin/projectpoint/create', [
            'project_id' => 1,
            'markerLat' => 5.287020206451416,
            'markerLong' => 51.68828138589033,
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        $this->assertDatabaseHas('interest_point', [
            'project_id' => 1,
            'location' => new Point(5.287020206451416, 51.68828138589033),
            'area' => null,
            'name' => 'TestCaseProjectPoint',
            'information' => 'This is a automated test ProjectPoint, please delete this point!',
            'category' => 'bezienswaardigheid'
        ]);

        /*
        $test = factory(ProjectPoint::class)->create();

        $this->post('admin/projectpoint/create', $test);

        $this->assertDatabaseHas('project_point', $test);
        */
    }

ProjectPoint model

class ProjectPoint extends Model
{
    use SpatialTrait;

    protected $table = 'interest_point';

    protected $fillable = ['project_id', 'name', 'information', 'category' ];

    protected $spatialFields = [
        'location',
        'area'
    ];

    public $timestamps = false;

    public function project()
    {
        return $this->belongsTo('App\Models\Project', 'project_id');
    }
}

The output of the test is:

Failed asserting that a row in the table [interest_point] matches the attributes {
    "project_id": 1,
    "location": {
        "type": "Point",
        "coordinates": [
            51.68828138589033,
            5.287020206451416
        ]
    },
    "area": null,
    "name": "TestCaseProjectPoint",
    "information": "This is a automated test ProjectPoint, please delete this point!",
    "category": "bezienswaardigheid"
}.

But I expect to see the test case succeed and when checking the database no records have been added to the database



via Chebli Mohamed

Laravel Using config() in request validation

I'm using laravel 5.8 and I want to use access global config() in Request validation class but it does not work

namespace App\Http\Requests;

use App\AppConstant;
use Illuminate\Foundation\Http\FormRequest;

class Something extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'url' => 'required',
            'category' => 'in:'.implode(",", config('app.categories').''
        ];
    }
}

and here is part of my config/app.php

return [

    'name' => env('APP_NAME', 'Laravel'),
    'categories' => [
        'games',
        'entertainment'
    ],


but the output is


Class App\Http\Requests\Something does not exist

when i remove config() from request file it works very well



via Chebli Mohamed

Configuration Laravel and Laravel File Manager

I have Laravel 5.8 and newest Laravel File Manager: https://github.com/UniSharp/laravel-filemanager I use this component with CKEditor.

I have standard lam.php:

<?php

/*
|--------------------------------------------------------------------------
| Documentation for this config :
|--------------------------------------------------------------------------
| online  => http://unisharp.github.io/laravel-filemanager/config
| offline => vendor/unisharp/laravel-filemanager/docs/config.md
 */

return [
    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
     */

    'use_package_routes'       => true,

    // // Use relative paths (without domain)
    // 'relative_paths'           => false,

    /*
    |--------------------------------------------------------------------------
    | Multi-User Mode
    |--------------------------------------------------------------------------
     */

    'allow_multi_user'         => false,

    'allow_share_folder'       => false,



    /*
    |--------------------------------------------------------------------------
    | Folder Names
    |--------------------------------------------------------------------------
     */

    // Flexible way to customize client folders accessibility
    // If you want to customize client folders, publish tag="lfm_handler"
    // Then you can rewrite userField function in App\Handler\ConfigHandler class
    // And set 'user_field' to App\Handler\ConfigHandler::class
    // Ex: The private folder of user will be named as the user id.
    'user_folder_name'         => UniSharp\LaravelFilemanager\Handlers\ConfigHandler::class,
    'shared_folder_name' => '',
    'thumb_folder_name' => '',
    'images_dir'            => '',
    'images_url'            => '/',
    'files_dir'             => '/',
    'files_url'             => '/',



    'folder_categories'        => [
        'file'  => [
            'folder_name'  => '/txt',
            'startup_view' => 'grid',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
            ],
        ],
        'image' => [
            'folder_name'  => '/photos',
            'startup_view' => 'list',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
                'application/pdf',
                'text/plain',
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Upload / Validation
    |--------------------------------------------------------------------------
     */

    'disk'                     => 'upload',

    'rename_file'              => false,

    'alphanumeric_filename'    => true,

    'alphanumeric_directory'   => true,

    'should_validate_size'     => false,

    'should_validate_mime'     => true,

    // permissions to be set when create a new folder or when it creates automatically with thumbnails
    'create_folder_mode'       => 0755,

    // permissions to be set on file upload.
    'create_file_mode'         => 0644,

    // If true, it will attempt to chmod the file after upload
    'should_change_file_mode'  => true,

    // behavior on files with identical name
    // setting it to true cause old file replace with new one
    // setting it to false show `error-file-exist` error and stop upload
    'over_write_on_duplicate'  => false,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail
    |--------------------------------------------------------------------------
     */

    // If true, image thumbnails would be created during upload
    'should_create_thumbnails' => false,

    // Create thumbnails automatically only for listed types.
    'raster_mimetypes'         => [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
    ],

    'thumb_img_width'          => 200,

    'thumb_img_height'         => 200,

    /*
    |--------------------------------------------------------------------------
    | jQuery UI options
    |--------------------------------------------------------------------------
     */

    'resize_aspectRatio'       => true,

    'resize_containment'       => true,

    /*
    |--------------------------------------------------------------------------
    | File Extension Information
    |--------------------------------------------------------------------------
     */

    'file_type_array'          => [
        'pdf'  => 'Adobe Acrobat',
        'doc'  => 'Microsoft Word',
        'docx' => 'Microsoft Word',
        'xls'  => 'Microsoft Excel',
        'xlsx' => 'Microsoft Excel',
        'zip'  => 'Archive',
        'gif'  => 'GIF Image',
        'jpg'  => 'JPEG Image',
        'jpeg' => 'JPEG Image',
        'png'  => 'PNG Image',
        'ppt'  => 'Microsoft PowerPoint',
        'pptx' => 'Microsoft PowerPoint',
    ],

    'file_icon_array'          => [
        'pdf'  => 'fa-file-pdf-o',
        'doc'  => 'fa-file-word-o',
        'docx' => 'fa-file-word-o',
        'xls'  => 'fa-file-excel-o',
        'xlsx' => 'fa-file-excel-o',
        'zip'  => 'fa-file-archive-o',
        'gif'  => 'fa-file-image-o',
        'jpg'  => 'fa-file-image-o',
        'jpeg' => 'fa-file-image-o',
        'png'  => 'fa-file-image-o',
        'ppt'  => 'fa-file-powerpoint-o',
        'pptx' => 'fa-file-powerpoint-o',
    ],

    /*
    |--------------------------------------------------------------------------
    | php.ini override
    |--------------------------------------------------------------------------
    |
    | These values override your php.ini settings before uploading files
    | Set these to false to ingnore and apply your php.ini settings
    |
    | Please note that the 'upload_max_filesize' & 'post_max_size'
    | directives are not supported.
     */
    'php_ini_overrides'        => [
        'memory_limit' => '256M',
    ],
];

```


and filesystem.php

```
'upload' => [
            'driver' => 'local',
            'root' => public_path('upload/web'),
            'url' => env('APP_URL').'/upload/web',
        ],

I would like to add files to the public / upload / txt directory

When creating a new directory, for example with the name SUMMER - it is located in public / upload / web / txt / summer. This is ok. When I add a new file to this directory, Laravel File Manager creates a new file called summerhttp / - and adds more folders in it: domain.test / upload / web / txt / fwfewfwe / myfile.jpg

How can I repair it?



via Chebli Mohamed

Laravel 5.6 - How to change storage folder directory?

The current project's storage folder directory is set to:

/www/httpdocs/storage/app/ProjectFiles/

But my server administrator has recommended to change it to:

/home/ProjectName/www/storage/app/ProjectFiles

The developer working on this project says that because it's Laravel, it needs to run from the server root? httpdocs? Is it a fixed requirement? Is there a way around this?

Thanks!



via Chebli Mohamed

Why is lazy loading nested relation for each item in collection end up loading same values as last item's relation?

When I lazy load a relation for every item in collection based on some condition, all items end up having the same relation loaded. That loaded relation for all items is the last item's relation.

I tried setting custom attribute like

$single->parent->filenames = Model::where('id', $id);

but it doesn't work either. Here is my code

$index->transform(function($single) use (&$i){

            if($single->content_type === 'type1') {

                $single->owner->parent->load('fileNames');

            } else if($single->content_type === 'type2') {

                //     $single->parent->file_names = Model::where('id', $single->owner->id);

                $single->owner->parent->load(['fileNames' => function($q) use ($single) {
                    $q->where('file_names.id', $single->owner->id);
                }]);

            }

            return $single;
        });

In case of 'type2', I want $single->parent->file_names to be having one entry with id that is given in where clause

But What I get is all items in collection ends up having the same value of parent->file_names attribute as the collection's last item's parent->file_names attribute.



via Chebli Mohamed

When do I have to use "many to many", "Has One Through", "Has Many Through" relationship in eloquent?

I'm just curious, when should I use the relation 'many to many', the relation 'has one through', the relation 'has many through'? Because I am sure, these three relations are quite implemented with one to one relations and one to many relationships.

example (taken from laravel documentation):

table :users

id

name

table :roles

id

name

table :RoleUser

id

user_id

role_id

the relation is enough to use one to many, namely 'user' has many 'roleuser' and 'role' has many 'roleusers'.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}



via Chebli Mohamed

SMTP BLOCK GMAIL ACCOUNT(mail goto spam and bounce mail)

I have applied smtp method for sending mail through api and frontend. i configure gmail for smtp and used AWS server but after 10 to 15 mail my gmail account block and not able to send mail. because of "ohio" region AWS not provide smtp.



via Chebli Mohamed

laravel .htaccess in root folder

I am following this article.

I am using laravel 5.6.

I moved .htaccess file from public to root and renamed server.php to index.php.

.htaccess :

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

RewriteEngine On

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

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

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

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]

But css and js files are not loaded.



via Chebli Mohamed

What's the best Laravel Eloquent way to structure this

If the question is not StackOverflow-y I don't mind moderators to close it, I couldn't decide.

I have the following models: Users, Groups, Regions, Cities... There are like 4 of them. Every user can have multiple relations to each entity (administrator, manager, participant and some others)

Should I do a Relations table as follows:

user_id | target_id | target_type | relationship_type
      1 |         2 |       group |           manager

And if so - how would I use Eloquent relations - HasManyThrough somehow?

Or is the Eloquent way something else? Maybe different tables for each entity (user_group, user_region) ?

The goal is to have each "Groups where Peter is admin in", "Regions where Jessica is participant" queried easily via Eloquent.



via Chebli Mohamed

How to filter in laravel using middleware?

I am trying to finer all active courses and here is what I've tried.

Middleware is called Status

public function handle($request, Closure $next)
    {
      $status = $request->status();
      if($status == 'active'){
        return view('admin.courses.index');
      }

        return $next($request);
    }

My route calls the middleware

Route::get('admin/courses/?active', 'Admin\CoursesController@index')->middleware('status');

My view has a button that calls the route

<a href="" style="margin-left:10px;" class="btn btn-success">
            Active <span class="badge badge-light"></span>
          <span class="sr-only">total courses</span></a>

This code is not filtering the records and I'm not sure what I'm doing wrong.



via Chebli Mohamed

Datatable make function not working with query function

when using query method on model with datatable, not working for mongodb.

Datatables::of(Member::query())->make(true);

FatalThrowableError in Builder.php line 2339: Type error: Argument 1 passed to Illuminate\Database\Query\Builder::setBindings() must be of the type array, object given, called in /var/www/html/trrain_circle/vendor/yajra/laravel-datatables-oracle/src/Engines/EloquentEngine.php on line 71



via Chebli Mohamed

Configuration Laravel file manager

I have problem with configuration this component: https://github.com/UniSharp/laravel-filemanager .

My lfm.php file:

return [
    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
     */

    'use_package_routes'       => true,

    // // Use relative paths (without domain)
    // 'relative_paths'           => false,

    /*
    |--------------------------------------------------------------------------
    | Multi-User Mode
    |--------------------------------------------------------------------------
     */

    'allow_multi_user'         => false,

    'allow_share_folder'       => true,



    /*
    |--------------------------------------------------------------------------
    | Folder Names
    |--------------------------------------------------------------------------
     */

    // Flexible way to customize client folders accessibility
    // If you want to customize client folders, publish tag="lfm_handler"
    // Then you can rewrite userField function in App\Handler\ConfigHandler class
    // And set 'user_field' to App\Handler\ConfigHandler::class
    // Ex: The private folder of user will be named as the user id.
    'user_folder_name'         => UniSharp\LaravelFilemanager\Handlers\ConfigHandler::class,
    'base_directory' => 'public',
    'shared_folder_name'       => 'upload',
    'thumb_folder_name'        => 'thumbs',
    'files_folder_name' => 'file',
    'images_folder_name' => 'img',



    'folder_categories'        => [
        'file'  => [
            'folder_name'  => 'upload',
            'startup_view' => 'grid',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
            ],
        ],
        'image' => [
            'folder_name'  => 'photos',
            'startup_view' => 'list',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
                'application/pdf',
                'text/plain',
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Upload / Validation
    |--------------------------------------------------------------------------
     */

    'disk'                     => 'public',

    'rename_file'              => false,

    'alphanumeric_filename'    => false,

    'alphanumeric_directory'   => true,

    'should_validate_size'     => false,

    'should_validate_mime'     => true,

    // permissions to be set when create a new folder or when it creates automatically with thumbnails
    'create_folder_mode'       => 0755,

    // permissions to be set on file upload.
    'create_file_mode'         => 0644,

    // If true, it will attempt to chmod the file after upload
    'should_change_file_mode'  => true,

    // behavior on files with identical name
    // setting it to true cause old file replace with new one
    // setting it to false show `error-file-exist` error and stop upload
    'over_write_on_duplicate'  => false,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail
    |--------------------------------------------------------------------------
     */

    // If true, image thumbnails would be created during upload
    'should_create_thumbnails' => false,

    // Create thumbnails automatically only for listed types.
    'raster_mimetypes'         => [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
    ],

    'thumb_img_width'          => 200,

    'thumb_img_height'         => 200,

    /*
    |--------------------------------------------------------------------------
    | jQuery UI options
    |--------------------------------------------------------------------------
     */

    'resize_aspectRatio'       => false,

    'resize_containment'       => true,

    /*
    |--------------------------------------------------------------------------
    | File Extension Information
    |--------------------------------------------------------------------------
     */

    'file_type_array'          => [
        'pdf'  => 'Adobe Acrobat',
        'doc'  => 'Microsoft Word',
        'docx' => 'Microsoft Word',
        'xls'  => 'Microsoft Excel',
        'xlsx' => 'Microsoft Excel',
        'zip'  => 'Archive',
        'gif'  => 'GIF Image',
        'jpg'  => 'JPEG Image',
        'jpeg' => 'JPEG Image',
        'png'  => 'PNG Image',
        'ppt'  => 'Microsoft PowerPoint',
        'pptx' => 'Microsoft PowerPoint',
    ],

    'file_icon_array'          => [
        'pdf'  => 'fa-file-pdf-o',
        'doc'  => 'fa-file-word-o',
        'docx' => 'fa-file-word-o',
        'xls'  => 'fa-file-excel-o',
        'xlsx' => 'fa-file-excel-o',
        'zip'  => 'fa-file-archive-o',
        'gif'  => 'fa-file-image-o',
        'jpg'  => 'fa-file-image-o',
        'jpeg' => 'fa-file-image-o',
        'png'  => 'fa-file-image-o',
        'ppt'  => 'fa-file-powerpoint-o',
        'pptx' => 'fa-file-powerpoint-o',
    ],

    /*
    |--------------------------------------------------------------------------
    | php.ini override
    |--------------------------------------------------------------------------
    |
    | These values override your php.ini settings before uploading files
    | Set these to false to ingnore and apply your php.ini settings
    |
    | Please note that the 'upload_max_filesize' & 'post_max_size'
    | directives are not supported.
     */
    'php_ini_overrides'        => [
        'memory_limit' => '256M',
    ],
];

This component work fine, but I have problem with upload path.

When uploading files, they get to upload (save) to storage/app - this is wrong path for me.

I would like the files to be saved here: public/upload (I want change path: storage/app to public/upload)

I am a beginner at Laravel and I have no ideas how to change it. :(

How can you fix it?



via Chebli Mohamed

Method hasRole of Zizaco/entrust always returns false

In my lasravel 5.7 app using https://github.com/Zizaco/entrust I have problem using hasRole method, as it always returns false, even in db I have valid rows. Calling in control app/Http/Controllers/PersonalController.php wrapped method:

public function get($id)
{
    $user            = User::find($id);
    $check_roles_as_text= $user->checkRolesAsText();
...

app/User.php :

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Auth\Passwords\CanResetPassword;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable implements JWTSubject
{
    use EntrustUserTrait;

    use Notifiable;
    protected $primaryKey = 'id';

   public function checkRolesAsText() {
        $arr= [];
        echo '<pre>$this->id::'.print_r($this->id,true).'</pre>'; // that shows 5 - my logged user
        // dd($this); // If uncomment out put below
        if ( $this->hasRole(ACCESS_ROLE_ADMIN) ) {
            $arr[]= ACCESS_ROLE_ADMIN_LABEL;
            echo '-1';
        }
        if ( $this->hasRole(ACCESS_ROLE_MANAGER) ) {
            $arr[]= ACCESS_ROLE_MANAGER_LABEL;
            echo '-2';
        }
        if ( $this->hasRole(ACCESS_ROLE_CUSTOMER) ) {
            $arr[]= ACCESS_ROLE_CUSTOMER_LABEL;
            echo '-3';
        }
        echo '<pre>$arr::'.print_r($arr,true).'</pre>';
        return $this->concatArray($arr);
    }
}

Checking slq tracement I see that user_id is null :

   SELECT `ad_roles`.*, `ad_role_user`.`user_id`     AS `pivot_user_id`, `ad_role_user`.`role_id`     AS `pivot_role_id` 
    FROM `ad_roles` 
    INNER JOIN `ad_role_user` on `ad_roles`.`id` = `ad_role_user`.`role_id` 
    WHERE `ad_role_user`.`user_id` is null 

Output of dd($this):

User {#368 ▼
  #primaryKey: "id"
  #connection: "mysql"
  #table: "users"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:19 [▼
    "id" => 5
    "username" => "Admin"
    "email" => "admin@mail.com"
    "password" => "$2y$10$vxBkNOEteK5GwP/j1VEDiutmR92XVW1ixSEEQ5ZMq6WPY4RkAO97S"
    "remember_token" => null
    "status" => "A"
    "account_type" => "I"
    "verified" => 1
    "verification_token" => null
    "first_name" => "Red"
    "last_name" => "Song"
    "phone" => "247-541-7172"
    "website" => "red_song@make_vote.site.com"
    "notes" => null
    "creator_id" => null
    "activated_at" => null
    "avatar" => "5.jpeg"
    "created_at" => "2018-03-25 12:39:36"
    "updated_at" => "2018-05-20 19:48:03"
  ]
  #original: array:19 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"

I do not see why in sql user_id is null and how to fix it?

Thanks!



via Chebli Mohamed

Laravel vue js mixins not getting function response

I am using laravel 5.8 with vue js. I have created a generalized function for post/get requests. The problem is, i am not getting the mixins function response. Here is my code :

TestComponent.vue

import GeneralMixin from '../mixins.js';
export default {
    mixins: [ GeneralMixin ],
    methods:{
        login: function (e) {
            response = this.testMixin();
            console.log(response);
        }
    }
}

mixin.js

export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {  
                return response;
            });
        }
    }
}

I am not getting response of function testMixin() . Can anyone help please



via Chebli Mohamed

mercredi 29 mai 2019

Doctrine criteria MEMBER_OF trouble

I use laravel-doctrine and try to use criteria. But when I use memberOf comparison I got an error "Unknown comparison operator: MEMBER_OF"

QueryExpressionVisitor which throws an error doesnt have "MEMBER_OF" case in SWITCH operator (walkComparison() method)

Criteria::create()->andWhere(
    Criteria::expr()->memberOf(':user', 'e.likedUsers')
);

how can I use memberOf comparison with criteria API?



via Chebli Mohamed

Undefined variable: data (laravel multiple image upload)

enter image description here

This is my controller for multiple image upload, I am getting an error saying, data is undefined on json_encode(data),, can some give me a solution?



via Chebli Mohamed

How to mapping nested json to database in laravel php?

I retrieve B employee data from API server and return Json data that contain the employee's position and also the subordinate of the B employee also with the subordinate from that B employee's subordinate. The JSON data also return the position_head that means the boss of B Employee. The JSON look like this,

{
    "msg": "OK",
    "DATA": {
        "id": "2",
        "name": "DEDE",
        "email": "dede@mail.com",
        "username": "dede@mail.com",
        "jabatan": "Chief Executive Officer",
        "bidang": null,
        "picture": "https://web.com/resource/2.png",
        "subordinate": [
            {
                "position_name": "GROUP HEAD  FINANCE & GENERAL AFFAIR",
                "staffs": [
                    {
                        "staff_name": "BIMA",
                        "staff_id": "3",
                        "staff_code": "bima@mail.com"
                    }
                ],
                "children": [
                    {
                        "position_name": "OPERATIONS MANAGER",
                        "staffs": [
                            {
                                "staff_name": "MONA",
                                "staff_id": "6",
                                "staff_code": "mona@mail.com"
                            }
                        ]
                    },
                    {
                        "position_name": "ACCOUNTS EXECUTIVE",
                        "staffs": [
                            {
                                "staff_name": "RINA",
                                "staff_id": "14",
                                "staff_code": "rina@mail.com"
                            },
                            {
                                "staff_name": "MIKE",
                                "staff_id": "5",
                                "staff_code": "mike@mail.com"
                            }
                        ]
                    },
                    {
                        "position_name": "HEAD OF FINANCE & ACCOUNTING",
                        "staffs": [
                            {
                                "staff_name": "Testing",
                                "staff_id": "17",
                                "staff_code": "testing"
                            },
                            {
                                "staff_name": "JOHN",
                                "staff_id": "4",
                                "staff_code": "johb@mail.com"
                            }
                        ]
                    }
                ]
            },
            {
                "position_name": "GROUP HEAD MARKETING & SALES",
                "staffs": [
                    {
                        "staff_name": "LAUREN",
                        "staff_id": "7",
                        "staff_code": "lauren@mail.com"
                    }
                ],
                "children": [
                    {
                        "position_name": "SALES MANAGEMENT",
                        "staffs": [
                            {
                                "staff_name": "LUKE",
                                "staff_id": "10",
                                "staff_code": "luke@mail.com"
                            }
                        ]
                    },
                    {
                        "position_name": "CUSTOMER CARE & CM",
                        "staffs": [
                            {
                                "staff_name": "WALKER",
                                "staff_id": "16",
                                "staff_code": "walker@mail.com"
                            },
                            {
                                "staff_name": "BARN",
                                "staff_id": "15",
                                "staff_code": "barn@mail.com"
                            }
                        ]
                    },
                    {
                        "position_name": "MARKETING & PRODUCT MANAGER",
                        "staffs": [
                            {
                                "staff_name": "SIRENE",
                                "staff_id": "9",
                                "staff_code": "sirene@mail.com"
                            }
                        ]
                    },
                    {
                        "position_name": "MARKET PERFORMANCE ANALYST",
                        "staffs": [
                            {
                                "staff_name": "GLENN",
                                "staff_id": "8",
                                "staff_code": "glenn@mail.com"
                            }
                        ]
                    }
                ]
            }
        ],
        "position_head": null
    }
}

The problem is I want to mapping the data and put it in database table User with this column,

id
position
staff_name
staff_code
parent_staff_id

How to do the task? any help will appreciate



via Chebli Mohamed

How does Laravel's ORM specify the sorted values for the data?

E.g: There is a field in the table called name, Name contains some user names, for example:

| name |
---------
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |
| Zoo |


What do you want to achieve, for example, I am passing a value now, for example, passing Q, then the returned data, that is, all the first letters Q are in front, like this:

| name |
-------------
| Queen |
| Qta |
| Asal |
| Codaya |
| Ostily |
| Zoo |


If you pass in a Z, it becomes like this:

| name |
------------
| Zoo |
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |


How is this requirement implemented in mysql?



via Chebli Mohamed

Laravel Command outputs different version of node than command line

I upgraded my node to v10.16.0 on a server containing a running Laravel instance.

This is the output after upgrade:

$ node -v
v10.16.0

This is the ouptut from running the Laravel scheduled command manually and echo-ing the response:

$ php artisan custom:command
v10.16.0

This is the output when that command is run by Laravel on it's 5 minute schedule:

v6.14.3

Laravel command is as follows:

$process = new Process("node -v");
$process->run();

How is this possible? Surely Laravel just runs a command on the command line in the same way you'd use exec() and thus should be on the same version. Even php artisan seems to get the right version.



via Chebli Mohamed

ReferenceError when running javascript in a Laravel Blade

I am trying to run a simple javascript function from app.js in a blade but I am getting a ReferenceError that the function is not defined.

The "app.js" was compiled with "npm run dev".

The file "app.js" in binded and I can see my function there.

app.js

require('./bootstrap');

function myTest()
{
    alert(1);
}

index.blade.php

@extends('layout')

@section('title', 'Some Title')

@section('content')
    Welcome
@endsection

@section('scripts')
    <script>myTest();</script>
@endsection

Source code

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="DeUaExASeRzE1Wl0OUAyVFhmHQ7DZNfbZR7kETJ7">
    <script src="http://127.0.0.1:8000/js/app.js"></script>
    <link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
    <title>WOG</title>
</head>
<body>
    <!-- ######### NavBar ######### -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container">
      <a class="navbar-brand" href="/">WOG</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown">
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link active" href="/">Home</a>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Module</a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                <a class="dropdown-item" href="/modules/alphanum">Alphanumerisch</a>
                <a class="dropdown-item" href="/modules/num">Numerisch</a>
              </div>
            </li>
          </ul>
        </div>
        </div>
      </nav>

    <!-- ######### Content ######### -->
    <div class="container">
            <h1>Willkommen</h1>
            <script>myTest();</script>
    </div>
  </body>
</html>

I was expecting to get a simple alert, but instead i am getting a "ReferenceError: myTest is not defined".

What can i do?

Thanks in advance



via Chebli Mohamed

Schema::dropIfExists() Deleted ALL tables in DB on migrate:rollback

I ran php artisan migrate:rollback on command line, so the migration deleted ALL TABLES in db.

There is only one migration created but have others tables in used db

The laravel documentation says: "To drop an existing table, you may use the drop or dropIfExists methods."

and the function down() on migration code is the default like as bellow:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('image')->unsigned()->nullable();
            $table->string('name', 64);
            $table->string('slug', 64)->unique();
            $table->integer('price')->unsigned();
            $table->timestamps();
        });
    }

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

I don't think the Schema::dropIfExists('products') work properlly in this case, this is a bug? or my(and laravel documentation) mistake?



via Chebli Mohamed

Can't seem to run my laravel code using xampp

So I downloaded an application from bitbucket that uses the laravel framework. When I tried running:

composer update

I get an error (listed below)

In ProviderRepository.php line 208:

  Class 'Spatie\Activitylog\ActivitylogServiceProvider' not found  


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Then when I try viewing it on my local host (using xammp) I get another error.

Parse error: syntax error, unexpected ‘const’ (T_CONST), expecting variable (T_VARIABLE) in /Users/sandeepsuri/Prepr_Web/vendor/symfony/http-foundation/HeaderUtils.php on line 21

I'm confused as to what the problem is and I'm not too sure how to fix it.



via Chebli Mohamed

Incorrect file upload path in Laravel

I am very beginner in Laravel.

I use Laravel 5.8 in my project.

I use this component: CkEditor + https://github.com/UniSharp/laravel-filemanager .

When uploading files, they get to upload to storage/app. I would like them to be available from the website and located in the folder: public/upload

My lfm.php file:

return [
    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
     */

    'use_package_routes'       => true,

    // // Use relative paths (without domain)
    // 'relative_paths'           => false,

    /*
    |--------------------------------------------------------------------------
    | Multi-User Mode
    |--------------------------------------------------------------------------
     */

    'allow_multi_user'         => false,

    'allow_share_folder'       => true,



    /*
    |--------------------------------------------------------------------------
    | Folder Names
    |--------------------------------------------------------------------------
     */

    // Flexible way to customize client folders accessibility
    // If you want to customize client folders, publish tag="lfm_handler"
    // Then you can rewrite userField function in App\Handler\ConfigHandler class
    // And set 'user_field' to App\Handler\ConfigHandler::class
    // Ex: The private folder of user will be named as the user id.
    'user_folder_name'         => UniSharp\LaravelFilemanager\Handlers\ConfigHandler::class,
    'base_directory' => 'public',
    'shared_folder_name'       => 'upload',
    'thumb_folder_name'        => 'thumbs',
    'files_folder_name' => 'file',
    'images_folder_name' => 'img',



    'folder_categories'        => [
        'file'  => [
            'folder_name'  => 'upload',
            'startup_view' => 'grid',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
            ],
        ],
        'image' => [
            'folder_name'  => 'photos',
            'startup_view' => 'list',
            'max_size'     => 50000, // size in KB
            'valid_mime'   => [
                'image/jpeg',
                'image/pjpeg',
                'image/png',
                'image/gif',
                'image/svg+xml',
                'application/pdf',
                'text/plain',
            ],
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Upload / Validation
    |--------------------------------------------------------------------------
     */

    'disk'                     => 'public',

    'rename_file'              => false,

    'alphanumeric_filename'    => false,

    'alphanumeric_directory'   => true,

    'should_validate_size'     => false,

    'should_validate_mime'     => true,

    // permissions to be set when create a new folder or when it creates automatically with thumbnails
    'create_folder_mode'       => 0755,

    // permissions to be set on file upload.
    'create_file_mode'         => 0644,

    // If true, it will attempt to chmod the file after upload
    'should_change_file_mode'  => true,

    // behavior on files with identical name
    // setting it to true cause old file replace with new one
    // setting it to false show `error-file-exist` error and stop upload
    'over_write_on_duplicate'  => false,

    /*
    |--------------------------------------------------------------------------
    | Thumbnail
    |--------------------------------------------------------------------------
     */

    // If true, image thumbnails would be created during upload
    'should_create_thumbnails' => false,

    // Create thumbnails automatically only for listed types.
    'raster_mimetypes'         => [
        'image/jpeg',
        'image/pjpeg',
        'image/png',
    ],

    'thumb_img_width'          => 200,

    'thumb_img_height'         => 200,

    /*
    |--------------------------------------------------------------------------
    | jQuery UI options
    |--------------------------------------------------------------------------
     */

    'resize_aspectRatio'       => false,

    'resize_containment'       => true,

    /*
    |--------------------------------------------------------------------------
    | File Extension Information
    |--------------------------------------------------------------------------
     */

    'file_type_array'          => [
        'pdf'  => 'Adobe Acrobat',
        'doc'  => 'Microsoft Word',
        'docx' => 'Microsoft Word',
        'xls'  => 'Microsoft Excel',
        'xlsx' => 'Microsoft Excel',
        'zip'  => 'Archive',
        'gif'  => 'GIF Image',
        'jpg'  => 'JPEG Image',
        'jpeg' => 'JPEG Image',
        'png'  => 'PNG Image',
        'ppt'  => 'Microsoft PowerPoint',
        'pptx' => 'Microsoft PowerPoint',
    ],

    'file_icon_array'          => [
        'pdf'  => 'fa-file-pdf-o',
        'doc'  => 'fa-file-word-o',
        'docx' => 'fa-file-word-o',
        'xls'  => 'fa-file-excel-o',
        'xlsx' => 'fa-file-excel-o',
        'zip'  => 'fa-file-archive-o',
        'gif'  => 'fa-file-image-o',
        'jpg'  => 'fa-file-image-o',
        'jpeg' => 'fa-file-image-o',
        'png'  => 'fa-file-image-o',
        'ppt'  => 'fa-file-powerpoint-o',
        'pptx' => 'fa-file-powerpoint-o',
    ],

    /*
    |--------------------------------------------------------------------------
    | php.ini override
    |--------------------------------------------------------------------------
    |
    | These values override your php.ini settings before uploading files
    | Set these to false to ingnore and apply your php.ini settings
    |
    | Please note that the 'upload_max_filesize' & 'post_max_size'
    | directives are not supported.
     */
    'php_ini_overrides'        => [
        'memory_limit' => '256M',
    ],
];

The traditional upload works correctly (uploads files to the public / upload directory):

$file->move(public_path($path), $uniqueName . '.' . $extension);

How can you fix it?



via Chebli Mohamed

How to pass form values to route

I'm having trouble passing a value from a form to a route.

{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!} Call Details

Route::post('reports/{report}', 'ReportController@index');



via Chebli Mohamed

Call to a member function details() on null?

My code is:

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

$user_details = [
            'name' => $request->name,
            'address' => $request->address,
            'lastname' => $request->lastname,
            'secondname' => $request->secondname,
            'inn' => $request->inn,
            'fincode' => $request->fincode,
        ];

$user->details()->create($user_details);

Model User is:

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    public function details()
    {
        return $this->hasOne(UserDetails::class, 'user_id', 'id');
    }

}

UserDetails model is:

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetails extends Model
{

    protected $table = 'enterprise';

    protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}



via Chebli Mohamed

ErrorException : symlink(): No such file or directory - problem with artisan

I'm very beginner in Laravel. I have Laravel 5.8 and MacOS. When I run this command:

artisan storage:link

I have error:

ErrorException  : symlink(): No such file or directory

  at /Users/trifek/Projects/php/laravel/project/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:252
    248|      */
    249|     public function link($target, $link)
    250|     {
    251|         if (! windows_os()) {
  > 252|             return symlink($target, $link);
    253|         }
    254| 
    255|         $mode = $this->isDirectory($target) ? 'J' : 'H';
    256| 

  Exception trace:

  1   symlink("/Users/trifek/Projects/php/laravel/project/storage/app/public", "/Users/trifek/Projects/php/laravel/project/public/storage")
      /Users/trifek/Projects/php/laravel/project/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:252

How can you fix it?

My problem is that when you upload files in: https://unisharp.github.io/laravel-filemanager/config - files are uploaded to storage / app / public / files / - instead of correct public / upload



via Chebli Mohamed

Export data to Excel file using Laravel Voyager

I want to export posts data from Admin Pannel i added a button in:

\vendor\tcg\voyager\resources\views\bread\browse.blade.php

<a href="">
                        <button id="export-to-excel" type="button" class="btn btn-danger">EXPORT</button>
                        </a>

i use Maatwebsite package.. i installed the package via composer..

Can anyone suggest me that what's I'm doing wrong.

My Code :

. .

Web.php:

Route::group(['prefix' => 'admin','as' => 'voyager.', 'middleware' => 'admin.user'], function()
 {
 Route::get('ExportCommandes','ExportController@getExport');
});

ExcelController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\browse;
use Input;
use Excel;

class ExcelController extends Controller
{
    //
    public function getExport(){
       $post=Post::all();
       Excel::create('Export Data', function($excel) use($post){
       $excel->sheet('Sheet 1', function($sheet) use($post){
          $sheet->fromArray($post);
       });
       })->export('xlsx');
     }   
}

ExportCommandes.blade.php:

@extends('voyager::master')



via Chebli Mohamed

Laravel responce returns empty but when I print and ran the query in db it works

This is the query code that I am using please look and help me out. I would really appreciate it

 DB::table('position as p')->addSelect(\DB::raw(
                 'p.*,(SELECT name from user where user.id=p.user_id) as name'
                 ))->addSelect(\DB::raw(
                         'DATE_FORMAT(p.created_at,"%H:%i") as time'
                        ))
                 ->whereRaw($wr)
                 ->whereRaw(
                    "(p.id =(SELECT id FROM position WHERE position.user_id=p.user_id AND Date(position.created_at)='".$date."' order by position.id asc limit 0,1) Or p.id =(SELECT id FROM position WHERE position.user_id=p.user_id AND Date(position.created_at)='".$date."' order by position.id desc limit 0,1))"
                  )
                 ->orderBy("p.user_id","asc")->orderBy("p.id",'asc')->get();



via Chebli Mohamed

Filter users after the role

I am very beginner in Laravel.

I have this code:

    class User extends Authenticatable implements MustVerifyEmail
    {
        use Notifiable;

        public static $roles = [];


        protected $fillable = ['company_id', 'enable', 'name', 'surname', 'email', 'email_verified_at', 'password', 'counter', 'url_address',  'isCompany', 'isMailing', 'content', 'nip1', 'business1', 'phone1', 'street1', 'number1', 'postal_code1', 'city1', 'country_id1', 'provincial_id1', 'nip2', 'business2', 'phone2', 'street2', 'number2', 'postal_code2', 'city2', 'country_id2', 'provincial_id2', 'nip3', 'business3', 'phone3', 'street3', 'number3', 'postal_code3', 'city3', 'country_id3', 'provincial_id3', 'cash', 'lng', 'lat', 'enable_map', 'remember_token', 'created_at', 'updated_at', 'last_login_at', 'last_login_ip' ];


        protected $hidden = [
            'password', 'remember_token',
        ];


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

        public function mainRole()
        {
            return $this->hasOne('App\Role');
        }




        public function hasRole(array $roles)
        {

            foreach($roles as $role)
            {

                if(isset(self::$roles[$role]))
                {
                    if(self::$roles[$role])  return true;

                }
                else
                {
                    self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                    if(self::$roles[$role]) return true;
                }

            }
            return false;
        }

    }
Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->string('url_address', 160);
            $table->boolean('isCompany')->default(0);
            $table->boolean('isMailing')->default(0);
            $table->text('content')->nullable();
            $table->string('nip1', 12)->nullable();
            $table->string('business1', 120)->nullable();
            $table->string('phone1', 60)->nullable();
            $table->string('street1', 150)->nullable();
            $table->string('number1', 8)->nullable();
            $table->string('postal_code1', 12)->nullable();
            $table->string('city1', 100)->nullable();
            $table->bigInteger('country_id1')->default(0);
            $table->bigInteger('provincial_id1')->default(0);
            $table->string('nip2', 12)->nullable();
            $table->string('business2', 120)->nullable();
            $table->string('phone2', 60)->nullable();
            $table->string('street2', 150)->nullable();
            $table->string('number2', 8)->nullable();
            $table->string('postal_code2', 12)->nullable();
            $table->string('city2', 100)->nullable();
            $table->bigInteger('country_id2')->default(0);
            $table->bigInteger('provincial_id2')->default(0);
            $table->string('nip3', 12)->nullable();
            $table->string('business3', 120)->nullable();
            $table->string('phone3', 60)->nullable();
            $table->string('street3', 150)->nullable();
            $table->string('number3', 8)->nullable();
            $table->string('postal_code3', 12)->nullable();
            $table->string('city3', 100)->nullable();
            $table->bigInteger('country_id3')->default(0);
            $table->bigInteger('provincial_id3')->default(0);
            $table->decimal('cash', 9, 2)->default(0);
            $table->decimal('lng', 10, 8)->default(0);
            $table->decimal('lat', 10, 8)->default(0);
            $table->boolean('enable_map')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });



Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });


Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

and seed:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);


        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

    }

I would like to display a list of users who have the ADMIN role.

I have this code:

public function showAdminList(string $query, string $sortColumn, string $sortMethod) {

return User::where('email', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('name', 'LIKE', '%' . $query . '%')->orWhere('surname', 'LIKE', '%' . $query . '%')->orderBy($sortColumn, $sortMethod)->paginate(25);

}

The above code shows me all the users I have in the database. How can I display only those users who have the ADMIN role?



via Chebli Mohamed