lundi 30 septembre 2019

Laravel support collection not works on the timing have any solution?

Laravel support collection does not work with the date and time. how can I solve it?

$timings = collect([]);

for ($i = 1; $i < 24 ; $i++) {
    $timings->push([
        'start_time' => $i.':50:34'
    ]);
}

Above loop is for the generate 24 hours timings for the example.

When we make this then works fine but include unnecessary timings also.

$timings->where('start_time', '<=', '11:59:59')->where('start_time', '>=', '00:00:00');
$timings->where('start_time', '>=', '12:00:00')->where('start_time', '<=', '23:59:59');

Please help me with this.



via Chebli Mohamed

import dlib ImportError: No module named dlib in Ubuntu 18.04

I am using .php file and calling one python file though Symfony Components which contains dlib and cv2. This python file works fine in terminal but calling from php file. It give an error.

Code

$process = Process::fromShellCommandline('python /home/machine/openface/demos/compare_two_pic.py {/home/machine/openface/demos/images/orange.jpg,/home/machine/openface/demos/images/orange.jpg}');

$process->run();

echo "here".$process->getOutput();

// executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        echo $process->getOutput();

Error Output:

Traceback (most recent call last):

File &quot;/home/machine/openface/demos/compare_two_pic.py&quot;, 
line 12, in &lt;module&gt;
import dlib
ImportError: No module named dlib


via Chebli Mohamed

How do I store files to a another location outside of Laravel 5.5 file structure

Hi first time posting here, I am developing an application using laravel 5.5 and currently uploading files in the public/storage directory using the symlink command. The application is hosted on an application server which is part of my organization's domain/network.

What I would like to do is save my files on another server already dedicated to file storage so as to ease up traffic on the application server.

I have created an 'FTP' configuration in the 'disks' array of config/filesystems.php as I saw in other examples but when the upload is executed I get "Could not connect to host: xx.xx.xx.xx on port 21". Below is the FTP config I added.

'ftp' => [
            'driver' => 'ftp',
            'host' => env('FTP_HOST'),
            'username' => env('FTP_USERNAME'),
            'password' => env('FTP_PASSWORD'),
            'root' => '/file_storage',
            'passive' => false,
            'port' => 21,
        ],

in my .env file, this is what I have

FTP_HOST=10.13.1.66
FTP_USERNAME=agriculture\foo
FTP_PASSWORD=bar

the line of code in the controller that calls the FTP array:

$file = $request->nid_file;
$doc = $individual->id.'_NIDScan_'.md5($file->getClientOriginalName()).'.'.$file->extension();
Storage::disk('ftp')->put($doc,$file);

additional information:

  • the domain name is agriculture
  • I have tried adding and removing agriculture\ in the FTP_USERNAME
  • tried adding \\ in front of the FTP_HOST IP address
  • tried setting passive to both true and false
  • changed port to 80
  • server OS is Windows.

Any help would be appreciated. Thanks.



via Chebli Mohamed

Laravel - websockets supervisor run error

I´ve been searching but all the answers i found didn´t resolve my problem, my system is centOS and i have followed this instructions with no luck, after that i saw other links, but at some point i´m confused and don´t know what is wrong anymore, so below is what i have done and hopping someone could help me out:

As the instructions say i went to /etc/supervisord.d and created a file called websockets.conf, inside i did this:

[program:websockets]
command=/usr/bin/php /home/gynkgo/artisan websockets:serve
numprocs=1
autostart=true
autorestart=true
user=root

After that, i did the supervisorctl update and then supervisorctl start websockets this last one returns: websockets: ERROR (no such process). This was when i satrted digging for some other solutions and found this so i went to /etc/supervisord.conf, edit the file i putted what is below:(the last version of what i tried)

[program:websockets]
process_name=%(program_name)s_%(process_num)02d
command=php /home/gynkgo/artisan websockets:serve
autostart=true
autorestart=true
user=root
numprocs=3
redirect_stderr=true

but still no luck at all, what am i missing? som epeople say i should have a /etc/supervisor directory but i don´t think that´s the solution, others say that that´s not needed.

Thanks for your time Regards



via Chebli Mohamed

Laravel session json to sting in blade

im using Laravel 5.8.30

i set a session ,, when i call session in blade page

 

its showing

[
   {
  "id": 2,
  "country_id": 18xxx
  "code": "vvv",
  "name": "vvvvvv",
  "shipping": "12345",
  "created_at": "2019-09-30 00:00:00",
  "updated_at": "2019-09-30 00:00:00"
 }
]

i got this output i need to specific details in string .. how can i show this in my blade page only single value

thanks in advance :)



via Chebli Mohamed

Image in a header componer in Laravel

I have a header component that I render with @include('components.header') and in this header I have a user image that I should fetch from the database. To save the user image in the database I created a helper table called user_images where I save the user id, the base64 image and the status. The logic leaves only the image that the user is using as status 1 and the others with status 0 (zero). I need to fetch this logged in user image and display it in the header, but I don't know which controller to use the search. I want to fetch the image and make it available as soon as I log in

$user = Auth::user();
    $localization = UserLocalization::find($user->id);
    if(!$localization){
        $localization = new UserLocalization;
    }
    $images = UserImage::where('user_id', $user->id)->get();
    $image = UserImage::where('status', 1)->where('user_id', $user->id)->first();
    // dd($image);
    return view('admin.profile.index')->with(\compact('user'))
                                        ->with(\compact('localization'))
                                        ->with(\compact('images'))
                                        ->with(\compact('image'));

This way the image is only available on the controller in question. I would like it to be available throughout the application after login.

Someone to help me do this?



via Chebli Mohamed

How you pass a named method to the fallback route in Laravel?

In Laravel routing there is fallback method:

Route::fallback(function () {
    //
});

A normal route is somethig like this:

Route::get('/user', 'UserController@list');

There is a way to use the fallback route like this:

Route::fallback('FallbackController@index');


via Chebli Mohamed

How to insert/assign evenly to all my vehicles the packages that are to be delivered?

I am new here please forgive me in case of formatting errors. I have a problem that's been troubling me these past few days. It involves assigning packages evenly among my delivery trucks. What my code does right now is it checks the counter for a column on my delivery_trucks table. If it reaches 10 total packages, it now moves on to the next delivery truck. Basically the first few trucks are loaded with packages while the other trucks have none to deliver. It delivers daily so it resets daily as well. How do i evenly assign packages to all my trucks? Here's my current code:

public function deliverPackages(Request $request)
{
      $package = $this->package;

      $packageid = $request['packageid'];
      $packagename = $request['packagename'];
      $qty = $request['qty'];
      $delivery_truck = DeliveryTruck::status()->package()->first(); -- This code right here is what i want to change
      $package->receiver__id = $request['receiver_id'];
      $package->deliverytruck_id = $delivery_truck->deliverytruck_id;
      $package->total = $request['total'];

      --and a few more unrelated code
}  

Status() checks if the truck is in working condition. A bit more information, how do i implement it if for example all my trucks from #1 to #10 each have 1 package. When all have been assigned a package each, it now returns to truck #1 and it repeats until all packages are assigned evenly to my trucks.



via Chebli Mohamed

Combinations of filters can be optional laravel eloquent relationships

I want to filter replies based on query parameter passed, query parameters can be post_id, comment_id and array of reply_ids all can be optional and can be used as combination

 $query = Post::where('user_id', auth()->id());
    if ( isset($data['reply_ids']) ) {
        $query = $query->with('posts.comments.replies')->whereHas('posts.comments.replies', function($query) use ($data){
            $query->whereIn('id', $data['reply_ids']);
        });
    }

Now, if I want to filter again with comment authors, that is on comments table, if I want to add filters of post author, that will be on posts table, how I can add those conditional, and still that will be optional?



via Chebli Mohamed

Retrieving eloquent api resource using keyby collection method

I have an end API point

users/{user}

now in User resource, I want to return

     public function toArray($request)
        {
            // return parent::toArray($request);

            return [
                'id' => $this->id,
                'name' => $this->name,
//                'comments' => $this->post->comments->keyBy('post_id')
                'comments' => new CommentCollection($this->post->comments->keyBy('post_id'))

            ];
        }

but the result will not include the post_id as key, how I can make it return the comments collection having key post_id?



via Chebli Mohamed

Laravel records not geting as dynamic

views/show.blade.php

@extends('layouts.app')
@section('content')
<h5>Showing Task </h5>
<div class="jumbotron text-center">
   <p>
      <strong>Task Title:</strong> <br>
      <strong>Description:</strong> 
   </p>
</div>
@endsection

Controllers/HomeController.php

public function show(Task $task)
{
   return view('show', compact('task', $task));
}

routes/web.php

Route::get('show/{id}', 'HomeController@show')->name('show');

views/viewalltask.blade.php

<td><a href=""></a></td>

No error / No Record / instead of particulr record display blank page



via Chebli Mohamed

Laravel : Access denied for user ''@'localhost' (using password: YES) after removing credentials from .env file

I have installed Laravel 6.0 and set up the database. Initially, it was working fine when I have put the database credentials in .env file but after removing it from .env file and setting up it in database.php file, I am getting this error.

Access denied for user ''@'localhost' (using password: YES)

What is wrong I am doing here?

Thanks J



via Chebli Mohamed

Cannot declare class App\Http\SeoInit\SeoInit, because the name is already in use

I am creating a helper function its show this error

Cannot declare class App\Http\SeoInit\SeoInit, because the name is already in use.

Thanks.



via Chebli Mohamed

How to switch Vue.js to production mode in Laravel?

Since Vue.js is comes already installed in Laravel, I'm not sure how to set it to production mode.

When I launch my website I get the message in console:

You are running Vue in development mode. Make sure to turn on production mode when deploying for production.



via Chebli Mohamed

How to add multiple images and text by using ajax and jquery in Laravel?

I want to add simple text and image multiple. I gone through jQuery and ajax and it's nice to apply for this concept. Please help with code example. Thanks



via Chebli Mohamed

How To Sort Accessors In Laravel?

I have a Character Model Which have some Accessors which counts some items related to this model. I cannot use orderby because column does not exist in db and cannot use sortby because we use datatables (with angular). In postgres may be possible with lateral join but am using mysql. Is any other way to do this ? Accessors ex.

protected $appends = [
     "changes_count"
];

public function getChangesCountAttribute()
{
    return $this->changes()->where('type', 'Change')->count();
}


via Chebli Mohamed

laravel vinkla pusher not install

don't install illuminate/support v5.5.43|don't install laravel/framework v5.8.35 - don't install illuminate/support v5.5.44|don't install laravel/framework v5.8.35 - Installation request for laravel/framework (locked at v5.8.35, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.35]. - Installation request for pusher/pusher-http-laravel ^4.2 -> satisfiable by pusher/pusher-http-laravel[v4.2.0, v4.2.1, v4.2.2].

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



via Chebli Mohamed

Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::type() [Laravel]

I'm trying to make a api that will return the type of a word (noun, pronoun, verb, etc.) after creating that word in the database. But for some reason I am getting a "Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::type()" error when the type method is clearly defined in my vocabulary model. Here are parts of the code for the application.

The first model is the type model it allows me to get the "contents" of a type (model not listed here) and the vocabularies that belongs to a specific type.

model-code-listing 1: VocType.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VocType extends Model
{
    public function contents()
    {
        return $this->hasMany('App\VocTypeContent');
    }

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

this second model allows me to create a word in the vocabulary table access its "contents", type and category. This is where the issue lies.

model-code-listing 2: VocVocabulary.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VocVocabulary extends Model
{
    protected $fillable = ['voc_category_id','type_id', 'name', 'context', 'picture'];
    public $timestamps = false;

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

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

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

The third model allows me to create the content of a vocabulary and access it parent vocabulary.

model-code-listing 3: VocVocabularyContent.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VocVocabularyContent extends Model
{
    protected $fillable = ['voc_vocabulary_id','lang_id', 'content', 'context', 'romanization', 'pronunciation', 'audio'];
    public $timestamps = false;

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

below are the three migrations used for the models listed above.

migration-code-listing 1: create_voc_types_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateVocTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('voc_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('abbreviation');
        });
    }

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

migration-code-listing 2: create_voc_vocabularies_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateVocVocabulariesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('voc_vocabularies', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('cat_id');
            $table->unsignedInteger('type_id');
            $table->foreign('cat_id')->references('id')->on('voc_categories')->onDelete('cascade');
            $table->foreign('type_id')->references('id')->on('voc_types')->onDelete('cascade');
            $table->string('name');
            $table->string('context');
            $table->string('picture');
        });
    }

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

migration-code-listing 3: create_voc_vocabulary_contents_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateVocVocabularyContentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('voc_vocabulary_contents', function (Blueprint $table) {
            $table->primary(['voc_id', 'lang_id']);
            $table->unsignedInteger('voc_id');
            $table->unsignedInteger('lang_id');
            $table->foreign('voc_id')->references('id')->on('voc_vocabularies')->onDelete('cascade');
            $table->foreign('lang_id')->references('id')->on('languages')->onDelete('cascade');
            $table->string('content');
            $table->string('context');
            $table->string('romanization');
            $table->string('pronunciation');
            $table->string('audio');
        });
    }

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

This is the controller where I am calling the type() method of vocabulary. basically I have an html form that sends a post request to this controller's method (postVocabularyAPI) if no id is provided in the request a vocabulary will be created (if the language is english). Then whether or not an id is provided with the request the method will create a vocabulary "content" for the given id (if no id is provided the given id will be the id of the previously created vocabulary). Then the postVocabularyAPI method will return a json response containing the id of the type of the vocabulary.

controller-code-listing 1: Vocabulearn.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Language;
use App\VocTheme;
use App\VocCategory;
use App\VocCategoryContent;
use App\VocVocabulary;
use App\VocVocabularyContent;
use App\VocType;

class Vocabulearn extends Controller
{

    //other methods above

    public function postVocabularyAPI(Request $request, $language, $theme, $category){

        $vocabulary_id = $request->vocabulary_id;
        if($vocabulary_id === NULL){
            if($language == "english"){
                $vocabulary = VocVocabulary::create([
                    'voc_category_id'   => VocCategory::where("slug", $category)->get()->first()->id,
                    'type_id'           => VocType::where("abbreviation", $request->type)->get()->first()->id,
                    'name'              => ucfirst(addslashes($request->translation)),
                    'context'           => $request->context,
                    'picture'           => ''
                ]);
                $vocabulary_id = $vocabulary->id;
            } else {
                echo '{"success":false, "message":"Create first the English Vocabulary"}';
            }
        }

        $vocabularyContent = VocVocabularyContent::where('lang_id', '=', Language::where("slug", $language)->get()->first()->id)
        ->where('voc_vocabulary_id', '=', $vocabulary_id)
        ->first();

        if($vocabularyContent !== NULL){
            $vocabularies = DB::table('voc_vocabulary_contents')
            ->where('lang_id', '=', Language::where("slug", $language)->get()->first()->id)
            ->where('voc_vocabulary_id', '=', $vocabulary_id)
            ->delete();
        }

        $vocabularyContent = VocVocabularyContent::create([
            'voc_vocabulary_id' => $vocabulary_id,
            'lang_id' => Language::where("slug", $language)->get()->first()->id,
            'content' => ucfirst(addslashes($translation)),
            'context' => addslashes($context),
            'romanization' => strtolower(addslashes($romanization)),
            'pronunciation' => $pronunciation,
            'audio' => $request->audio
        ]);

        echo '{"success":true, "type":"'.stripslashes(html_entity_decode($vocabularyContent->vocabulary()->type()->id)).'"}';
    }
}

doing this gives me a

"Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::type()"

even when I change

echo '{"success":true, "type":"'.stripslashes(html_entity_decode($vocabularyContent->vocabulary()->type()->id)).'"}';

by

echo '{"success":true, "type":"'.stripslashes(html_entity_decode($vocabularyContent->vocabulary()->get()->first()->type()->id)).'"}';

I get an error stating

"Call to a member function type() on null"

which isn't right because the database was properly populated so I shouldn't be getting a null vocabulary.



via Chebli Mohamed

Odd Laravel apiResource routes issue

the route for my show function in an apiResource is not working, but if I overload the route and point to the function it works as expected.

resource route does note work

Route::apiResource('/delivery_handler/chat/','CartDeliveryListChatController');

working route

Route::get('/delivery_handler/chat/{id?}', function ($id) {
        return (new App\Http\Controllers\Api\CartDeliveryListChatController)->show($id);
    });

in my controller

    /**
     * @param $chatId
     * @return CartDeliveryListChatResource
     */
    public function show($chatId): CartDeliveryListChatResource
    {
        $data = CartDeliveryListChat::where('id',$chatId)->first();
        return new CartDeliveryListChatResource($data);
    }

the routes list

  | GET|HEAD  | api/v1/delivery_handler/chat/{id?}                  |                                   | Closure                                                                             | api          |
|        | GET|HEAD  | api/v1/delivery_handler/chat/{}                     | show                              | App\Http\Controllers\Api\CartDeliveryListChatController@show                        | api          |


via Chebli Mohamed

Can we get the total record count and the first record only in the same eloquent query?

Can we get the total record count and the first record only in the same eloquent query?

I know we can get the total records via below eloquent queries:

1. Model::count();

2. Collection Method
   Model::all()->count();

And we can get the first record like this:

Model::first();

I have one solution for the same i.e.

$data = Model::all();

1. $count = count($data);
2. $count = $data->count();

And for the first row/data

1. $firstRecord = $data[0];
2. $firstRecord = $data->first();


via Chebli Mohamed

Laravel React authentication

I'm new to react, what I'm trying to achieve is user login using react components in laravel.

https://github.com/000kelvin/laravel-react-authentication

I followed this and I installed everything.When I'm running this project I seem to get error regarding prop. Terminal asked me to update react and react-dom that I already updated

Laravel 5.8; npm 6.4.1; react@16.2.0; react-dom@16.2.1

import LoginContainer from './LoginContainer';
import {withRouter} from "react-router-dom";
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: props.location,
    };
  }
  render() {
    return (
      <div className="content">
        <LoginContainer redirect={this.state.redirect} />
      </div>
    )
  } 
}
export default withRouter(Login)

Showing out this Error:

Warning: Failed prop type: Invalid prop 'component' supplied to 'Route': the prop is not a valid React component in Route (created by Testlog) in Testlog



via Chebli Mohamed

class 'Pusher\Pusher' not found required in laravel package

I'm creating my own Laravel package and I required Pusher server in my package, in my composer.json there is a pusher required and I also checked it in vendor folder also exist ... and when I'm trying to use it in my package controller like use Pusher\Pusher; it says that class 'Pusher\Pusher' not found!!!

Does anyone have a solution?? Thanks in advance.



via Chebli Mohamed

dimanche 29 septembre 2019

Showing error angular.js:12477 TypeError: $(...).intlTelInput is not a function

I have a tab service prvider which shows details of customer while clicking the tab shows empty fields to edit with an error angular.js:12477 TypeError: $(...).intlTelInput is not a function after refresing the page the error will disappear what will be the issue

I have put my intlTelInput function inside a timeout function but didint work.

this is my code if( $("input[name='code']").length >= 1){ $("input[name='code']").intlTelInput({ separateDialCode:true, initialCountry: "auto", geoIpLookup: function(callback) { $.getJSON("https://freegeoip.net/json/", function (data) { callback(data.country_code);` }); } });} This is my error angular.js:12477 TypeError: $(...).intlTelInput is not a function at Object. (http://localhost/taskm-rio/public/admin/app/ng-controllers/providerController.js:104:49)

enter image description here



via Chebli Mohamed

laravel5: does not exist on this collection instance

I have an error

does not exist on this collection instance.

In my show .blade.php, I want to show ten featured posts.

So in my controller I used get() method. And in my view page, I used @foreach. But it doesn't work.

Instead of get(), I used first(). Then It worked. I could show only the latest post.

But it is not what I want to accomplish. Because

I want to show the ten latest posts.

ResultsController.php

public function show($id,Post $post)
{
    $particular_post= Post::find($id);
    $featured_posts = Post::latest()->limit(10)->get();

    $posts['particular_post'] = $particular_post;
    $posts['featured_posts'] = $featured_posts;

    return view('posts.show',compact('posts'));
}

show.blade.php

 @foreach($posts['featured_posts'] as $featured_post)
        <div class="swiper-container">
        <div class="swiper-wrapper">

            <div class="swiper-slide">
                <div class="image">
                    <img src="" alt="" width="300px" height="200px">
                </div>
                <div class="card-information">
                        <div class="event-name">
                            
                        </div>
                        <div class="heart">
                            <i class="fas fa-heart fa-lg" style="color: #F70661"></i>
                        </div>
                    <div class="event-date">
                        
                    </div>
                    <div class="card-info">
                        <p>
                            <a href="#" style="color: white">...see more</a>
                        </p>
                    </div>
                </div>    
            </div>
            @endforeach

web.php

Route::get('results/{id}', 'ResultsController@show')->name('posts.show');


via Chebli Mohamed

Python Shell script not called in Symfony

I am using Ubuntu 18.04 and I have implemented openFace library which works fine through terminal that takes two input parameter containing name of images

Terminal command

python /home/machine/openface/demos/compare_two_pic.py {/home/machine/openface/demos/images/5G5X0dnI5xkD.jpg,/home/machine/openface/demos/images/orange.jpg}

I just pasted this command in Symfony but i didn't get any result.

$process = new Process(['python2', '/home/machine/openface/demos/compare_two_pic.py {/home/machine/openface/demos/images/5G5X0dnI5xkD.jpg,/home/machine/openface/demos/images/orange.jpg}',$arg(optional)]);

        $process->run();
echo "here".$process->getOutput();

// executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        echo $process->getOutput();

I make a web service to just call a function and check. Is this function working or not? The output of function



via Chebli Mohamed

Whats the difference between @if and @can in laravel

Were making a project with different users. I noticed that I can use @if to prevent specific user from a specific function but I can also use @can. Can someone tell me what are thier differences. I did not register any policies in AuthServiceProvider but I can still use @can method. I'm just referring to the type of user. I'll show you some code.

Can

   @can($global_user->role != 0)
            <li class="">
              <a href="" onclick="return LoadingOverlay();">
                <i class="fa fa-list"></i>
                <span>Issue Tracker</span>
              </a>
            </li>
  @endcan

If

   @if($global_user->role != 0)

        <li class="">
          <a href="" onclick="return LoadingOverlay();">
            <i class="fa fa-child"></i>
            <span>Students</span>
          </a>
        </li>
@endif

Edit: Can I also use @can inside @if statements like this?

    @if($global_user->role != 0)
        <li class="treeview
            
            
            ">
          <a href="#">
            <i class="fa fa-bug"></i> <span>System Issues</span>
            <span class="pull-right-container">
              <i class="fa fa-angle-left pull-right"></i>
            </span>
          </a>
          <ul class="treeview-menu">

            <li class="">
              <a href="" onclick="return LoadingOverlay();">
                <i class="fa fa-edit"></i>
                <span>Report an Issue</span>
              </a>
            </li>


            @can($global_user->role != 3)
            <li class="">
              <a href="" onclick="return LoadingOverlay();">
                <i class="fa fa-list"></i>
                <span>Issue Tracker</span>
              </a>
            </li>
            @endcan


          </ul>
        </li>
        @endif


via Chebli Mohamed

Login with two different roles

I have an admin which can create several recordings in the form Members.

In the table Members, there are 2 fields user_id and team_id.

Here is an example below:

enter image description here

Now, my problem is that I want to log for example with the user jeremy@gmail.com.

I have to see only my informations. Here is an example:

enter image description here

DataBase:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('team_id')->unsigned()->nullable();
            $table->foreign('team_id')->references('id')->on('teams');
            $table->timestamps();
        });
    }

 public function up()
        {
            Schema::create('teams', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->integer('user_id')->unsigned()->nullable();
                $table->foreign('user_id')->references('id')->on('users');
                $table->timestamps();
            });
        }

I'm trying to understand the syntax to do?

 public function index(Request $request)
    {   

        $user = $request->user();
        $members = Member::query()
        ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
         $query->where('id???', $user->email); ????
        })
        ->when($request->has('search'), function (Builder $query) use ($request) {
        $query->where('name??', 'like', '%' . $request->input('search') . '%');
         })->with('team:id,name') 
        ->paginate(5);

        return view('admin.members.index', compact('members'))
        ->with('display_search', $user->hasRole('admin'));

    }

Thank you in advance for your help.



via Chebli Mohamed

Get search results from database in laravel with LIKE

I have built a search form in a laravel project. Where search is working fine. But the client wants something like if someone searches with terms G51.0, G51.1, G51.2 and so on, then it should also show the row of G51 from the database. But my search result is showing the specific result of G51.0 or G51.1 or G51.2 and so on. I have also used "LIKE" in the controller but no luck. The data in the table is in German language. Here is my controller code...

$search = CsvData::where('k_rperbereich', 'LIKE', "%$request->korperbereich%")->orWhere('diagnose', 'LIKE', "%$request->korperbereich%")->get();
    return view('search-result', compact('search'));


via Chebli Mohamed

Laravel - send mailable content to API

I'm working on a project which is built using Laravel and we have different events when we need to send an email. Until now we used SMTP but due to our company security policy we need to create a micro-service which will take care of sending emails.

My project will make a request with the email template and the email service will send it.

To send an email I'm using Laravel's "mailable" objects and the templates can contain HTMLL & CSS.

The plan is to use "guzzlehttp/guzzle"library for the requests. But my problem is that I don't know how to send my template content in order to keep the styling.

What I found until now is that I can render an template:

 $string = (new GroupEnrollment($group, $user))->render();

But this returns me as string which is rendered like in the picture bellow:

enter image description here

What I also found is that now you can render the "mailable" directly in the browser for a preview:

return  new GroupEnrollment($group, $user);

This is rendered how I need, but this is the mailable object and I don't see the template in his properties.

enter image description here

From what I see that are services like MailGun that are API based so there should be a way to get the correct format. Any idea how can I do this?



via Chebli Mohamed

Relationships retrieve user emails

I'm trying to understand how I can join the tables users and teams to members in fact ?

Users Table:

id |   name  |         email          |     password
 1     alain        alain@gmail.com          *****
 2     eric         eric1@gmail.com          *****

Teams Table:

id |     name          
 1      R.O.S    
 2      Stephanois   

Members Table:

id |     user_id  (email)        |    team_id (name)
 1          1                             1
 2          2                             1

DataBase:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

public function up()
    {
        Schema::create('members', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('team_id')->unsigned()->nullable();
            $table->foreign('team_id')->references('id')->on('teams');
            $table->timestamps();
        });
    }

 public function up()
        {
            Schema::create('teams', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->integer('user_id')->unsigned()->nullable();
                $table->foreign('user_id')->references('id')->on('users');
                $table->timestamps();
            });
        }

User Model:

protected $fillable = [
        'name', 'email', 'password',
    ];

public function team(){
        return $this->hasOne('App\Team', 'user_id', 'id'); ?
    }

public function member(){
        return $this->hasMany(??????????);
    }

Team Model:

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

public function member(){
        return $this->hasMany('App\Member', 'team_id'); ?
    }

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

Member Model:

protected $fillable = [
        'id', 'user_id', 'team_id'
    ];

public function team(){
    return $this->belongsTo('App\Team', 'team_id');
    }

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

I thank you in advance for your help



via Chebli Mohamed

How secured is laravel S3 temporary URL?

I would like to know if providing temporary url to access AWS bucket objects are secured in a sense that it discloses the AWS Access Key.

From my knowing if using IAM user's access key for accessing AWS bucket rather than root Access key can be highly secured if the IAM user is only permitted to read/write S3 services.

Are there any disadvantages of providing temporary url to the public using IAM user's access key?

Regards.



via Chebli Mohamed

Trapping FTP/SFTP errors in Laravel 5

I have a Laravel 5 backend that can store files using different protocols based upon user configuration. Currently I am supporting FTP and SFTP and am trying to gracefully trap the errors in order to alert the user to the fact that there may be an issue with their (S)FTP server.

Since this is a common routine that also writes to local storage, I am trying to make sure that I trap all errors that are related to (S)FTP while still trapping "regular" errors.

In my testing, I have disabled my FTP server and then my SFTP server and in doing so noticed that they generate entirely different exceptions when I try to connect. For example,

FTP - Runtime Exception

SFTP - Logic Exception

My understanding is that Laravel uses Flysystem but I cannot seem to find any documentation on all the possible errors that could occur when using (S)FTP and am wondering if someone can point me in the right direction on where to find it.



via Chebli Mohamed

How get common sum of stripe express in callback control action

I added "stripe/stripe-php": "^7.2" to my Laravel 5.8 app and looking how stripe works https://stripe.com/docs/legacy-checkout/php I see example with sum :

 $charge = \Stripe\Charge::create([
      'customer' => $customer->id,
      'amount'   => 5000,
      'currency' => 'usd',
  ]);

but above code in control action is triggered in callback redirect stripe method. That is different control when I calculated total sum(several product on different sun can be selected ) and show view with “Pay with Card” button. Question is how to send $5000 to this control action ? I suppose I can remember $5000 in sessions and read it callback control action, but is it good way?

Also are some other fields like description, items list which can be sent to stripe request?



via Chebli Mohamed

Voyager Addition field options

im using Voyager Laravel to build my app, but im having some issues regarding the form fields, in my Bread column of "transmission" i have included in the json form this:

column transmission:

{
    "options": {
        "option1": "Automática",
        "option2": "Manual"
    }
}

In the admin is displaying well the information, the problem is when i call it in the frontend for example:

$car->transmission -> outputs -> "option1"

Im trying to find in the documentation regarding calling only the text/label of the option1 that is correct, but no information im finding.

Anybody the uses Voyager had the same issue?



via Chebli Mohamed

How to get the balance column in php lararavel?

I have a db table gl_trans

enter image description here

This is my expected output.

enter image description here

This is my source code so far.


        $start_date = (!empty($_POST["start_date"])) ? ($_POST["start_date"]) : ('');
        $data = $usersQuery
        ->select(
            'gl_trans.tran_date as date2', 
            'gl_trans.account as account2', //GET ACCCOUNT COLUMN
             DB::raw('(CASE WHEN gl_trans.amount >= 0 THEN gl_trans.amount ELSE 0 END) AS debit'), //GET DEBIT COLUMN
             DB::raw('(CASE WHEN gl_trans.amount < 0 THEN -gl_trans.amount ELSE 0 END) AS credit'), // GET CREDIT COLUMN
             DB::raw('(debit - credit) AS current_balance'),
             DB::raw('(SELECT sum(amount) FROM gl_trans WHERE tran_date < "'.$start_date.'" AND account = account2 and amount >= 0 ) AS debit_open_balance'), //SUM OF PREVIOUS DATE OF DEBIT VALUES (POSITIVE AMOUNT)
             DB::raw('(SELECT sum(amount) FROM gl_trans WHERE tran_date < "'.$start_date.'" AND account = account2 and amount < 0 ) AS credit_open_balance'), //SUM OF PREVIOUS DATE OF CREDIT VALUES (NEGATIVE AMOUNT)
             DB::raw('( SELECT (CASE 
                WHEN current_balance >= 0 
                THEN (COALESCE(debit_open_balance, 0) - COALESCE(-credit_open_balance, 0) + current_balance) 
                ELSE (COALESCE(debit_open_balance, 0) - COALESCE(-credit_open_balance, 0) - current_balance) end)) as balance') // GET BALANCE COLUMN USING THE CURRENCT BALANCE 
         ) 
        ->orderBy('date2', 'ASC')
       ->get();

My problem is that I can't get the exact value of debit_open_balance and credit_open_balance using the $star_date as it should get the tran_date of the row but it is not unique. I have tried using the id > current_id but it will not get the exact amount because the data is being ordered as date.

Note: Opening balance is the (total positive amount - total negative amount) of the previous date (< $start_date)

Please help thank you.



via Chebli Mohamed

use dynamic value in a config file

i have config file for payments, i should use dynamic value (that is loading from db) for merchant-id key:

in AppServiceProvider in boot method i write this

 $zarinpal = PaymentConfig::where('slug', 'zarinpal')->first();

        config()->set(['app.zarinpal' => ['merchant' => $zarinpal->merchant ?? 0]]);

but config('app.zarinpal')["merchant"] value is null there... how can i fix this issue?

return [

    //-------------------------------
    // Timezone for insert dates in database
    // If you want Gateway not set timezone, just leave it empty
    //--------------------------------
    'timezone' => 'Asia/Tehran',

    //--------------------------------
    // Zarinpal gateway
    //--------------------------------
    'zarinpal' => [
        'merchant-id'  => config('app.zarinpal')["merchant"],//'xx',
        'type'         => 'zarin-gate',             // Types: [zarin-gate || normal]
        'callback-url' => '/',
        'server'       => 'germany',                // Servers: [germany || iran || test]
        'email'        => 'email@gmail.com',
        'mobile'       => '09xxxxxxxxx',
        'description'  => 'description',
    ],


via Chebli Mohamed

JWT Token Signature could not be verified error with external API login

In Laravel 5.8 / vuejs / vuex / mysql app I use jwt-auth and when I login into the system (standart auth with mysql users table) I use method :

export function setAuthorizationToken(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}

and it worked ok.

Next I remade SignUp/SignIn to use external API for SignUp/SignIn operations. So my app needs to make SignUp/SignIn with external API , but also I have requests for controls of my app to read/write data from/to mysql.

I remade SignIn request to external API with php curl in control action when user clicks SignIn button, like :

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

   // I run login method
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/login');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));

            $userLoginData = [
                'email'    => $credentials['email'],
                'password' => $credentials['password'],
            ];
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userLoginData));

            $resp = curl_exec($ch);

            $respArray = json_decode($resp);
            if ( isset($respArray->success) and empty($respArray->success)) { // login fails - return error in responce
                $err = curl_error($ch);
                curl_close($ch);

                $errorsArray     = [$respArray->data];
                $errors_message  = $respArray->data;

                return response()->json([
                    'error_code' => 1,
                    'message'    => $errors_message,
                    'errors'     => $errorsArray,
                    'rows_total' => 0,
                ], HTTP_RESPONSE_BAD_REQUEST /*HTTP_RESPONSE_INTERNAL_SERVER_ERROR*/);

            } //if ( isset($respArray->success) and empty($respArray->success)) { // login fail

            $logged_user_token = $respArray->data->token;
            // if login was successfull I keep token





             // I need to get details of the logged user
            $loggedUser= null;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/user');

            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Content-Type: application/json; charset=utf-8",
                "Authorization: Bearer ".$logged_user_token
            ]);


            $resp = curl_exec($ch);

            $respArray = json_decode($resp);
            if ( isset($respArray->success) and empty($respArray->success)) { // details read fails - return error in responce
                $err = curl_error($ch);
                curl_close($ch);

                $errorsArray     = [$respArray->data];
                $errors_message  = $respArray->data;

                return response()->json([
                    'error_code' => 1,
                    'message'    => $errors_message,
                    'errors'     => $errorsArray,
                    'rows_total' => 0,
                ], HTTP_RESPONSE_BAD_REQUEST );

            } //if ( isset($respArray->success) and empty($respArray->success)) {
            $loggedUser= $respArray->data->customer_details;

//            $this->respondWithToken($logged_user_token);

            return response()->json(['error_code' => 0, 'message' => '', "token" => $logged_user_token, 'user'=> $loggedUser ], HTTP_RESPONSE_OK );
            // if user details read was successfull I return logged user

        }   // if( !empty($this->useAdmindashApi) and !empty($this->admindashApi)) {

But the problem is when I read data from my mysql db with app controls, I got

Token Signature could not be verified

in console. I suppose that jwt-auth knows nothing about token I read from external API in $logged_user_token var. Is there is a way to write value from $logged_user_token to jwt-auth token in my control above ?

"laravel/framework": "5.8.*",
"tymon/jwt-auth": "^1.0.0",


"vue": "^2.5.17",
"axios": "^0.18",
"vuex": "^3.1.0"

Thanks!



via Chebli Mohamed

Auth::user()->id return null laravel 5.8

I use laravel 5.8 when user login successfully return me to admin panel & auth::user()->name return the name of the user and when I add extraction from a click from admin panel the auth:: user()->name return null

this is a login home or admin controller enter image description here

this is login controller enter image description here

this the addExtraction controller enter image description here

this the web.php enter image description here



via Chebli Mohamed

Laravel 5.5.* SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed

I am trying to add a new user to my database using the RegistrationController provided by Laravel. Every time I try to register a new user it hits me with an error saying a not null constraint has failed, even though I am not submitting any null fields. At first I thought it was a problem specifically with the address field until I made it nullable in my migration to get around the error, and the not null constraint on the next field also failed. I have double checked all my migration files, and even dumped the data I'm trying to pass into the database to double check nothing is null. The error message tells me it's not even trying to pass the information I've provided to the database, but I have no idea how to fix this problem.

My migration:

    Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('address');
            $table->string('user_type');
            $table->boolean('approved')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

My create function in the Register Controller:

    protected function create(array $data)
    {
        return User::create([
            'address' => $data['address'],
            'name' => $data['name'],
            'email' => $data['email'],
            'user_type' => $data['user_type'],
            'password' => Hash::make($data['password'])
        ]);
    }

The result of my data dump:

       array:7 [▼
  "_token" => "d5qCwoIqyfiF1q5FyAIhi3gHEm5CA7OHpDZVRKSI"
  "name" => "test"
  "email" => "asasdfasd@sdfgsdfgg.com"
  "address" => "1637 test street"
  "user_type" => "Customer"
  "password" => "12345678"
  "password_confirmation" => "12345678"
]

And the error I'm getting:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: 
users.address (SQL: insert into "users" ("name", "email", "password", "updated_at", "created_at") 
values (test, asasdfasd@sdfgsdfgg.com, $2y$10$q1Kc0A80cd0ARJbvTtpiee59fJ8g4orilFWjNV5igihPDWQeoYhjG, 2019-09-29 08:57:58, 2019-09-29 08:57:58))

Any help anyone could provide me would be greatly appreciated. If you need any more snippets of my code please let me know. Thanks in advanced.



via Chebli Mohamed

How to redirect admin to admin dashboard if login is ajax?

I have Ajax Login in Laravel 5.8 that work fine but I need to redirect admin users to the admin dashboard but since the login is performed using Ajax I was thinking to return response contain indication that this user is admin and then make JQuery redirect that admin to admin dashboard. is there some other recommended way? and what about security especially that I will use policies on dashboard page to check if the redirected user is really admin and have the corresponding privileges (not relying on JQuery just using it to redirect)? I know this question may seem naive but I want to make sure there is no other better way, would you please kindly answer me?



via Chebli Mohamed

Is it possible to pass data from laravel controller then to component vue?

I am new to vue can I ask how to pass data variable from my controller to vue component

here is my controller

$categories = Category::all();

return  view('dashboard.index',compact('categories');

in my dashboard.index I want to grab that variable to my vue component, but I have no idea how.

Thank you in advance.



via Chebli Mohamed

samedi 28 septembre 2019

SQLSTATE[23000]: Integrity constraint violation in laravel5.8.35

I am very new to laravel and sqlite and am trying to create a new 'dish' to my list of dishes, however, once I submit the creation form I receive the following error: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: dishes.user_id (SQL: insert into "dishes" ("name", "price", "user_id", "updated_at", "created_at") values (Supreme Pizza, 15, ?, 2019-09-29 05:43:42, 2019-09-29 05:43:42))

I have tried a number of different modifications in my web.php, DishController, UserController, and the create.blade.php form itself, but none of the changes have worked. There were some similar questions asked here but none of the solutions helped my particular problem either.

This is my web.php file

Route::resource('dish', 'DishController');
Route::resource('user', 'UserController');

Auth::routes();

Route::get('/', 'UserController@index');
Route::get('/show/{id}', 'UserController@show');
Route::get('/show/{id}', 'UserController@create');
Route::get('users/{user}',  ['as' => 'users.edit', 'uses' => 'UserController@edit']);
Route::patch('users/{user}/update',  ['as' => 'users.update', 'uses' => 'UserController@update']);

Route::get('/dish', 'DishController@index');
Route::get('/show/{id}', 'DishController@show');
Route::get('/dish/create', ['as' => 'dish.create', 'uses' => 'DishController@create']);
Route::get('dishes/{dish}',  ['as' => 'dish.edit', 'uses' => 'DishController@edit']);
Route::patch('dishes/{dish}/update',  ['as' => 'dishes.update', 'uses' => 'DishController@update']);
Route::get('/dish/{dish}', 'DishController@destroy');

The relevant part of my DishController:

 public function index()
    {
        $dishes = Dish::all();
        return view('dishes.index')->with('dishes', $dishes);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return View::make('dishes.create_form')->with('users', User::all());

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'price' => 'required|integer|min:1',
            'user' => 'exists:user,id'
        ]);

        $dish = new Dish();
        $dish->name = $request->name;
        $dish->price = $request->price;
        $dish->user_id = $request->user;
        $dish->save();
        return redirect("dish/$dish->id");
    }

And the relevant part of my create_form:

<form method="POST" action=''>
        
        <p><label>Name: </label><input type="text" name="name" value=""></p>
        <p><label>Price: </label><input type="text" name="price" value=""></p>
        <p><select name="Restaurant">
        @foreach ($users as $user)
            @if ($user->role == 'restaurant')
            <option value="" selected="selected"></option>
            @endif
        @endforeach
        </select></p>
        <input type="submit" value="Create">
    </form>

The general idea is that I list my users that have a 'role' of 'restaurant' and when I click on one, it takes me to the dishes they have (i.e. lists all dishes with selected user_id), and the option to create a new dish.

When I try to create a new dish, I input all necessary data and submit the form but I get the error message as seen in the Title. It says that dishes.user_id is null, and shows it as '?'.

This is odd since the POST data shows that:

        name = "Supreme Pizza"
        price = "15"
        Restaurant = "7" (which is correct)

I can't for the life of me figure out what the problem is, so any help would be greatly appreciated.



via Chebli Mohamed

Hiding template and how if option selected

Can I ask some help I have select option and I want to show the form base on selected option but I cannot to get it working here is my code.

    <template>

        <div class="column is-12">
            <div class="box">
                <div class="field">
                    <label class="label">Category:  </label>
                    <div class="control">
                        <div class="select">
                            <select v-model="selectedValue">
                                <option v-for="category in categories.data"  :value="category.id" ></option>
                            </select>
                        </div>
                    </div>
                </div>


                <myform1-form v-show="selectedValue === 1"></myform1-form>
                <myform2-form v-show="selectedValue === 2"></myform2-form>

            </div>
        </div>


</template>

<script>
    export default {
        data(){
            return{
                categories: [],
                selectedValue: null,
                showForm: false
            }
        },
        mounted(){

            axios.get('api/category_api').then(response=> this.categories = response.data);
        }
    }
</script>


via Chebli Mohamed

Single column not being updated in laravel 5

I am tying to update a single column of a table messages and I have the following code:

  public function messageSeen(Request $request){
        $data = Message::find($request->id);
        $success = Message::where('id', $request->id)->update(array('is_seen' => 1));
        if($success){
            return response()->json(['status'=>'success'], 200);
        } else {
            return response()->json(['status'=>'Data not updated'], 404);
        }
    }

I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?



via Chebli Mohamed

SplFileInfo::getSize(): stat failed for C:\xampp\tmp\php9F9D.tmp

my cv 28 coulum.but not save save cv and show SplFileInfo::getSize(): stat failed for C:\xampp\tmp\php9F9D.tmp info please help me.

public function storeCv(Request $request) { $this->validate($request, [enter code here` 'full_name' => 'required', 'cvImage' => 'required', ]); $cvImage=$request->file('cvImage');

    $name = $cvImage->getClientOriginalName();
    $uploadPath = 'public/productImage/';
    $cvImage->move($uploadPath, $name);
    $imageUrl = $uploadPath . $name;
    $this->saveCvInfo($request, $imageUrl);

    return redirect('/cv/add')->with('message', 'Cv info save successfully');


    //echo '<pre>';
    // print_r($productImage);
}`


via Chebli Mohamed

laravel 5.8 Auth::user null after verified authentication

I've upgraded a laravel 5.4 to 5.8 project and added in some vue files vs blades and noticed that at some point along the way Auth::user() started to return null.

I reset all Auth files to laravel default from a fresh project, still returns null. I checked config files for auth and session variables per other post suggestions, no resolution. I can successfully Log::debug out that the AuthenticatesUsers.php 'authenticated' method logs out the Auth::user() successfully. When I move to another route from /login, i.e /browse, logging out Auth::user() immediately returns null.

I've php artisan cleared cache, config, and routes, run composer dump-autoload. My User model has all necessary traits and the DB uses 'id' as primary key. I can't figure out why I'm losing authentication immediately after logging in.

web.php:

Auth::routes();

Route::group(['middleware' => ['web']], function () {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/browse', 'ListingController@index')->name('listings');
});


via Chebli Mohamed

how to add a new column with laravel 5 not in list

i have query with mySQL like this select cust_name, 'c' from customer...

how to code in laravel? I have try like this...but error

    $customer = DB::table('customer')
        ->select('cust_name','c' as kode);


via Chebli Mohamed

what is 'resource missing' in stripe funds transfer in laravel?

I am trying to use transfer api in laravel app but i am getting this error "No such destination :'stripe account id'. when i check log of stripe account i found that resource is missing.

this is log

Request POST body

 {
   "amount": "400",
  "currency": "usd",
   "destination": "acct_180W54CRJ51SjjGi"
 }

Response body

{
   "error": {
     "code": "resource_missing",
     "doc_url": "https://stripe.com/docs/error-codes/resource-missing",
     "message": "No such destination: acct_180W54CRJ51SjjGi",
     "param": "destination",
     "type": "invalid_request_error"

   }
 }

here is the code

 \Stripe\Stripe::setApiKey('App key');

      $transfer=  \Stripe\Transfer::create([
            "amount" => 400,
            "currency" => "usd",
            "destination" => "acct_180W54CRJ51SjjGi",

          ]);
          return $transfer;

I want to transfer funds in destination account



via Chebli Mohamed

why it keep saying Image source not readable

Image source not readable

i have a issue to upload a image dear community please help me out

public function update(User $user)
{
    $data= tap(request()->validate([
        'f_name'=>'required',
        'l_name'=>'required',
        'email'=>'email|required',
        'phone'=>'required|numeric',
        'birthdate'=>'required|date',
        'adress'=>'required',

    ]),function(){
            if(request()->hasFile('image')){
                request()->validate([
                    'image'=>'file|image|max:5000',]);

            }

    });

    $user->update($data);

    $this->StoreImage($user);

    request()->session()->flash('msg','customer has been Updated successfully');

    return redirect('/user/unActive');
}

private function StoreImage($user){

    if(request()->has('image')){
        $user->update([
            'image'=>request()->image->store('uploads','public'),
        ]);

    $image= Image::make(public_path('storage/'.$user->image))->fit(300,300);
    $image->save();


    }
}

}

private function StoreImage($user){

    if(request()->has('image')){
        $user->update([
            'image'=>request()->image->store('uploads','public'),
        ]);

    $image= Image::make(public_path('storage/'.$user->image))->fit(300,300);
    $image->save();


    }

Intervention \ Image \ Exception \ NotReadableException Image source not readable



via Chebli Mohamed

I am lost in my relationships in Laravel?

I have a table payments with 6 fields: date_payment, fk_student, number_seance, price, total.

I also have a table named students with 5 fields: id, user_id, name, email, payment_id.

I have a table user with 3 fields: name, email, password.

I am lost in my relationships in Laravel

Model Student:

protected  $fillable = ['user_id', 'name', 'email', 'payment_id'];

public function payments(){

    return $this->hasMany('App\Payment', 'fk_student');
}


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

Model Payment:

protected  $fillable = ['date_payment', 'fk_student', 'number_seance',  'price', 'total'];

public function student(){

    return $this->belongsTo('App\Stuent', 'fk_student');
    }

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

Model User

public function student()
{
    return $this->hasOne('App\Student', 'user_id', 'id');
}

public function payments()
{
    return $this->hasOne('App\Student', 'payment_id', 'id');
}


via Chebli Mohamed

How do i filter for examples titles of some movies using a letter in Laravel 5?

So I'm trying to filter through the titles using a letter that is in an <a href></a> tag in Laravel 5 which should show me all the titles whose name start with that letter. What should i add in my view,controller and route to make that happened?



via Chebli Mohamed

Do I need live stripe account id to transfer funds in laravel?

I am trying to transfer funds with stripe API but it is giving error that No such destination exist. here is the code

   \Stripe\Stripe::setApiKey('App key');

      $transfer=  \Stripe\Transfer::create([
            "amount" => 400,
            "currency" => "usd",
            "destination" => "acct_1FN******",

          ]);
          return $transfer;

I make a new account and give that account's id.but it is still giving me that error?

Do i need live account stripe id?



via Chebli Mohamed

I always have the same student which appears after each recording

When I add a recording, I always have the same student which appears ???

I think the problem is perhaps in my function index() ?

public function index(Request $request)
  {   
     $user = $request->user();
     $payments = Payment::query()
     ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
     $query->where('email', $user->email);
     })
     ->when($request->has('search'), function (Builder $query) use ($request) {
    $query->where('name', 'like', '%' . $request->input('search') . '%');
         })->with('students:id,name') 
    ->paginate(5);

    return view('admin.payments.index', compact('payments'))
    ->with('display_search', $user->hasRole('admin'));
    }

For information my table students has 2 fields (id, name) and the table payments has 6 fields (id, date_payment, number_seance, price, total, fk_student).

Thank you for your help.



via Chebli Mohamed

How to upload and run a script with laravel?

I want to write a php script (say A) which run an uploaded typescript (say B) which was uploaded with a CRUD (input file form).

I know how to upload files like images, and I guess that uploading a ts script which is a text file is not very different, but I have no idea how am I supposed to run this new script on a page...

Anyone can help ?



via Chebli Mohamed

Upload Image to DB by Laravel 5.8

I'm trying to upload image from my folders to DB by PHPMyAdmin using laravel

inside ProductController.php the store method:

 public function store(Request $request)
     {
      Product::create($request->all());
      $formInput=$request->except('ImgSource');

   //        validation
         $this->validate($request,[
             'Name'=>'required',
             'Price'=>'required',
             'type'=>'required',
             'ImgSource'=>'image|mimes:png,jpg,jpeg|max:10000',
         ]);
   //        image upload
         $image=$request->file('ImgSource');
         if($image){
             $imageName=$image->getClientOriginalName();
             $image->move('images',$imageName);

             $formInput['ImgSource']=$imageName;

         }

         Product::create($formInput);
         return redirect()->route('product.index');
     }

and in the web.php

Route::resource('product','ProductsController'); and I use the form in create.blade.php

        <div class="form-group">
            
            
        </div>

It stores in the table products as C:\xampp\xampp1\tmp\php46F9.tmp what should I do to add correct images?



via Chebli Mohamed

How can I get the value of this variable?

In logout function, I need to get the value of $time. This variable was declared in other function, when user logged in.

Broadcast::channel('chat', function ($user) {
        $ip = Request::ip();
        $time = now();  
        if (auth()->check() && !session()->has('name'))  {  
            UserInfo::storeUser();
            session()->put('name',$user->name);
            return [
                'id' => $user->id,
                'ip' => $ip,
                'name' => $user->name,
                'joined' => $time,                   
            ];
        }
    });

When user logged out, I have to check his 'id' and value of 'joined'. How can I do this?

public function logout() {
       $id = auth()->id();
       $info = \App\UserInfo::where('id', $id)
                             -> where('joined', $time)
                             ->update(['left' => now()]);
        auth()->logout();
        session()->forget('name');
        session()->put('left',now());
        return redirect('/');
    }


via Chebli Mohamed

Laravel where :: model, how to add multi statement

So how i can add multi statement to query in ::where model.

Actually it lok like that: certs::where('unique', '=', $newUnique )->get()

i need somethig like that:

certs::where('unique, num', '=', $newUnique,$key )->get()

so in sql look like that

Select * From certs Where unique = $newUnique AND num = $key

I need that to check if data need to be updated or inserted.



via Chebli Mohamed

Execute "chown -R www-data:www-data /path" from laravel controller?

Is there a way to execute the command chown -R www-data:www-data /path from a laravel controller?



via Chebli Mohamed

Laravel 5.8 Auth::attempt function not working

I'm building a laravel app and login suddenly stopped working. The failure appears to be on the attempt function. I don't know what the problem is since the credentials are being passed accurately as they are on the database.

Here is a dump of the function on the AuthenticatesUsers class

protected function attemptLogin(Request $request)
{
    dd($this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    ));
}

Result: false

Here is a dump of the output to the Attempting class

public function __construct($guard, $credentials, $remember)
{

    $this->guard = $guard;
    $this->remember = $remember;
    $this->credentials = $credentials;


    dd($this->guard,$this->credentials,$this->remember,);
}

Result:

"web"
array:2 [▼
  "email" => "johnmarkwachira@gmail.com"
  "password" => "password"
]
true


via Chebli Mohamed

Whenever I create folder with Laravel Command I get "Permission denied" on edit or delete

I have controller that creates images and stores them in a new folder. When I go to the admin panel and create a new image a folder is automatically created with all the right permissions.

The problem comes when I do the absolutely same operation, but with a Laravel command, which I registered in the Kernel.

The command uses the same controller and the same functions but the permissions are all wrong, it creates the image and the directory, but after that it is unusable. I can't edit or delete it.

The only way to fix it is to run chown -R www-data:www-data /var/www/ in the server terminal.

I already tried to make the folder with mkdir($filePublicPath, 0755, true) but the issue remains. How can I fix this? How to make a directory with the laravel command and have good permissions?



via Chebli Mohamed

No Docker Setup - lookup example.com on 127.0.0.11:53: no such host error

I haven't install and setup docker but at all my laravel projects it gives me lookup example.com on 127.0.0.11:53: no such host error error.

All local projects serve on 80 port.

Laravel version: 5.7

I even don't know what causes the error, what should I share to describe my problem well..



via Chebli Mohamed

Syntax for a request in laravel (2 tables)

I have a table named Payments and another table named Students with the field name.

In my Controller Payment, I want to retrieve the student names.

I have this:

public function index(Request $request)
    {   
        $user = $request->user();
        $payments = Payment::query()
        ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
            $query->where('email', $user->email);
        })
        ->when($request->has('search'), function (Builder $query) use ($request) {
            $query->where('name', 'like', '%'.$request->input('search').'%');
        })
        ->paginate(5);



        return view('admin.payments.index', compact('payments'))
        ->with('display_search', $user->hasRole('admin'));
    }

How do I join the students table?

payment::whereHas('students'

I don't know where I have to put this line

Thank you for your help.



via Chebli Mohamed

vendredi 27 septembre 2019

what is No such destination in stripe?

I am trying to transfer amount from 1 stripe account to another stripe account but I am getting this error "No such destination:".

I tried to add different client ids. But it isn't working.

\Stripe\Stripe::setApiKey('APP Key');

      $transfer=  \Stripe\Transfer::create([
            "amount" => 400,
            "currency" => "usd",
            "destination" => "ca_FtG3t5**********",
            "transfer_group" => "ORDER_95"
          ]);
          return $transfer;

I want this to transfer amount to other stripe account.



via Chebli Mohamed

How to fix 'PHP code not working in laravel public folder'

I embed a php in one of my views with:

<iframe src="/game/game.blade.php" width="1519" height="690"></iframe>

In this file I have the following code:

<script>
    var userID = ;
    var userCredit = ;
</script>

I get the following error: Uncaught SyntaxError: Unexpected token '{'

I already tried to use etc. I also tried to embed a link that used a route to another view but with this I got a 403 forbidden error.

Does anyone know how I could fix this? or have another solution for me?



via Chebli Mohamed

Hasrole with 2 tables

I have a model named Student with the field name , here is the function, which is correct.

public function index(Request $request)
    {   
        $user = $request->user();
        $students = Student::query()
        ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
            $query->where('email', $user->email);
        })
        ->when($request->has('search'), function (Builder $query) use ($request) {
            $query->where('name', 'like', '%'.$request->input('search').'%');
        })
        ->paginate(5);

        return view('admin.students.index', compact('students'))
        ->with('display_search', $user->hasRole('admin'));
    }

Now, in my model Payment I have a request with 2 tables (Payment & Student).

Here is my function index()

public function index(Request $req) 
    {
    if ($req->search == "") {
        $payments = Payment::paginate(5);
        return view('admin.payments.index', compact('payments'));

    } else {

        $validated = $req->validate([
            'search' => 'alpha', 
        ]);

        $payments = payment::whereHas('students', function($query) use($req) {
            $query->where('name', 'like', '%' . $req->search . '%');
        })->paginate(5);
        return view('admin.payments.index', compact('payments'));

        }

    }

My problem is I want to adapt my function for connect me with an user.

I have this for now ???

public function index(Request $request)
{   
   $user = $request->user();
   $payments = Payment::query()
   ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
   $query->where('email', $user->email);
   })
   ->when($request->has('search'), function (Builder $query) use ($request) {

how to include this:

$payments = payment :: whereHas ('students', function ($ query) use ($ req) {
$query-> where ('name', 'like', '%'. $ req-> search. '%');


via Chebli Mohamed

$ is not defined Laravel 5.8

This got me so confused, I am not using the layouts.app of make:auth.

Here's my head tag of my layouts.master

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="csrf-token" content="">

<title>ZIAN PAYROLL SYSTEM</title>
<link rel="stylesheet" href="/css/app.css">
<link rel="stylesheet" href="">

and here's my script:

<script>
    $('#promote').on('show.bs.modal', function(event){
        var button = $(event.relatedTarget)
        var name = button.data('myname')
        var id = button.data('myid')
        var modal = $(this)

        console.log(id);
        modal.find('.modal-body #myname').val(name);
        modal.find('.modal-body #myid').val(id);
    })  
</script>

Followed some steps here in stack yet nothing helped. I know that removing the defer in the script would work but mine wouldn't.



via Chebli Mohamed

Connection for a user

I have for my table 'Student' 5 fields id, name, firstname, email, phone.

My question: I would like the user to connect by putting his name what should I change?

public function index(Request $request)
    {   
        $user = $request->user();
        $students= Student::query()
        ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
            $query->where('email', $user->email);
        })
        ->when($request->has('search'), function (Builder $query) use ($request) {
            $query->where('name', 'like', '%'.$request->input('search').'%');
        })
        ->paginate(5);



    return view('admin.students.index', compact('students'))
        ->with('display_search', $user->hasRole('admin'));
    }

Here:

$query->where('email', $user->email);

I have to put this?

  $query->where('name', $user->name);

Thank you for your help.



via Chebli Mohamed

Get hidden attribute of a model specified using Model::with()

In a controller, I use this code to get all Text objects and their associated authors

return Text::with('author')->get();

This is part of a backend only available to admins, and I need them to be able to access the author's name field. But in the author's model, I set protected $hidden = ['name']; when I programmed another part of my app that's for standard users.

Is there a way to use with, but get some hidden attribute? Or the other way round, to declare some attribute as hidden temporarily when using with?

Please note this is question is about the use of with in combination with hidden attributes. I'm not looking for something like $authors = $authors->makeVisible(['name']); (which is explained here).



via Chebli Mohamed

How to implement select2 in laravel

I have simple input I would like to user select js select2js

Here is my input

<div class="form-group">

    <select class="js-example-basic-multiple form-control" name="states[]" multiple="multiple">
        <option value="AL">Alabama</option>
        ...
        <option value="WY">Wyoming</option>
    </select>

    <!-- Button trigger modal -->

</div>

in my app.blade.php (master) i have this

$(document).ready(function() {
              $('.js-example-basic-multiple').select2()
            });
        </script>

Now when I run my app I get this error

caught TypeError: $(...).select2 is not a function
    at HTMLDocument.<anonymous> (create:420)
    at j (jquery.min.js:1197)
    at k (jquery.min.js:1203)

NOTE: in console network both js and CSS for select2 are loaded

What is wrong with my code?



via Chebli Mohamed

Convert Currency to Text using Laravel

I need to round currency amount and convert to text.

For example:

If a number is 12,34,000/- then output will be "12 lakhs".



via Chebli Mohamed

Modify unique attribute validation in Laravel

Trying to customize the error message for unique attribute. Tried changing my validation.php.

    'custom' => [
        'email' => [
            'unique:users' => 'Oops, email is taken. Please try again!'
        ]
    ],

and I call the validation in controller:

    request()->validate([
        'email' => 'unique:users',
        'password' => 'required|min:3',
    ]);

And I still get this:

The email has already been taken.



via Chebli Mohamed

Method File::deleteDirectory leaves some subdirectories non deleted

In my laravel 5.8 app in envoy task I delete old derectories with method :

use Illuminate\Support\Facades\File;
   ...

   File::deleteDirectory($directory_name);

But opening server's dirs are see that directories are not delete, but have some subdirectories inside. When the 1 directory is not deleted, like removing directory

/var/www/html/Hostels2Deployed/release/20190725-191130 

I found it with 1 subdirectory

/var/www/html/Hostels2Deployed/release/20190725-191130/storage/framework/cache/data# ls -la
total 16
drwxrwxrwx 4 lardeployer www-data 4096 Sep 27 11:59 .
drwxrwxrwx 3 lardeployer www-data 4096 Sep 27 11:59 ..
drwxr-xr-x 3 www-data    www-data 4096 Jul 25 16:12 cb
drwxr-xr-x 3 www-data    www-data 4096 Jul 25 16:12 ed

Why they are not deleted and how to delete it?

Thanks!



via Chebli Mohamed

Request->file returns null why?

So I'm trying to create a Video store of sorts in which you can see the image of the movie, title, lenght and the option to delete it. The problem is when I try to upload an image it always returns null. Also I use Laravel 5.8.35

I tried with getClientOriginalExtension but it can't work since file returns null

Slika means Image

Žanr means Genre

Naslov means Title

Godina means Year

Filmovi means Movies

Trajanje means Lenght

Akcija means Action

index.blade.php

<style>
    table,tr,td {
        border: 1px solid black;
    }

    table {
        border-collapse: collapse;
        width: 800px;
        font-size: 30px;
        font-weight: bold;
        text-align: center;
        align-self: center;
    }
</style>

<table>
    <tr style="background-color:lightgray">
        <td>Slika</td>
        <td>Naslov filma</td>
        <td>Godina</td>
        <td>Trajanje</td>
        <td>Akcija</td>
    </tr>
    @foreach($filmovi as $film)
    <tr>
    <td><img src="" alt=""></td>
        <td></td>
        <td></td>
        <td> minuta</td>
        <td> <a href="" data-method="delete">[obriši]</a></td>

    </tr>
    @endforeach

    <div class="">
        <a href="" class="btn btn-primary">Dodaj novi film</a>
    </div>

create.blade.php

<div>

        <form action="" method="post">
 Naslov: <br>
 <input type="text" class="form-control" id="naslov" name="naslov">
 <br>
 Žanr: <div class="select">
    <select name="zanr" id="zanr">
        @foreach($zanr as $z )
    <option value=""></option>
        @endforeach
      </select>
</div>

  Godina: <div class="select" style="width:200px;">
    <select name="godina" id="godina">
         @for($i = (int)date("1900"); $i<=(int)date("Y"); $i++)
        <option value="" name="godina" ></option>
         @endfor
    </select>
  </div>

  Trajanje: <br>
  <input type="text" class="form-control" id="trajanje" name="trajanje">
  <br>

  Slika: <br>
  <form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="slika" class="form-control" enctype="multipart/form-data">(max. 64 KB)
  <div class="form-group">
        <a href="" class="btn btn-primary">Natrag</a>
        <button type="submit" class="btn btn-success float-right">Objavi</button>
    </div>
  </form>
        </form>
 </div>

controller

<?php

namespace App\Http\Controllers;

use App\Filmovi;
use App\Zanr;
use Illuminate\Http\Request;
use App\Traits\UploadTrait;

class FilmoviController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

     use UploadTrait;
    public function index()
    {
        $filmovi = Filmovi::all();

        return view('filmovi.index', compact('filmovi'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $zanr = Zanr::all();

        return view('filmovi.create', compact('zanr'));
    }

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


        $filmovi = Filmovi::create([
            'naslov'   => request('naslov'),
            'id_zanr'    => request('zanr'),
            'godina'  => request('godina'),
            'trajanje' => request('trajanje'),
            'slika' => request('slika'),
        ]);

        if($request->has('slika'))
    {
        dd($slike = $request->file("slika"));

        $dirpath = '/uploads/slike/';

        $path=$dirpath . $slike;

        $this->uploadOne($slike, $dirpath, 'public');

        $filmovi->slika = $path;

    }
    $filmovi->save();

        return redirect()->route('filmovi.index');    
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Filmovi  $filmovi
     * @return \Illuminate\Http\Response
     */
    public function show(Filmovi $filmovi)
    {
        //
    }

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Filmovi  $filmovi
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $filmovi = Filmovi::find($id);
        $filmovi->delete();

    //   \Mail::to($post->user)->send(new PostDeleted($post));

        return redirect()->route('filmovi.index');
    }

}

UploadTrait

<?php 
namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait UploadTrait
{
    public function uploadOne(UploadedFile $uploadedFile, $dirpath = null, $disk = 'public')
    {
        $file = $uploadedFile->storeAs($dirpath, $uploadedFile,$disk);

        return $file;
    }
}
?>


via Chebli Mohamed

Change app path of a Laravel 5.5.46 application

I designed a Laravel application using the path suggested in the documentation:

folders:
- map: /var/www/virusapp
  to: /home/vagrant/code

Everything worked fine. Now I'm developing more applications so I changed my folders data to:

folders:
    - map: /var/www/virusapp
      to: /home/vagrant/virusapp
    - map: /var/www/pinetus
      to: /home/vagrant/pinetus

The initial virusapp cannot find the views anymore even though I haven't changed anything except my folders path. Please help me.



via Chebli Mohamed

how i can solve unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?) in laravel 5.5

controller

 public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'body' => 'required',
        'cover_image' => 'image|nullable|max:1999'
    ]);

    // Handle File Upload
    if($request->hasFile('cover_image')){
        // Get filename with the extension
        $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
        // Get just filename
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        // Get just ext
        $extension = $request->file('cover_image')->getClientOriginalExtension();
        // Filename to store
        $fileNameToStore= $filename.'_'.time().'.'.$extension;
        // Upload Image
        $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
    } else {
        $fileNameToStore = 'noimage.jpg';
    }

    // Create Post
    $post = new Post;
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->user_id = auth()->user()->id;
    $post->cover_image = $fileNameToStore;
    $post->save();

    return redirect('/posts')->with('success', 'Post Created');

i enabled this extension

extension=php_fileinfo.dll

my laravel version 5.5

when i upload image i getting this error

Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)

i think error on image validation

any one have idea about that??



via Chebli Mohamed