mardi 31 mars 2020

How to use select function and with function together in laravel

I want to select some column from the main table with laravel with function but when I use select it gives null in with for example

table1::select('column1','column2')->with(['table2'])->paginate($request->query('per_page', 10));

If I use select then it gives null in table2 but if I remove the select then it gives values in table2.

Can anyone please let me know what I am doing wrong or what can be done here



via Chebli Mohamed

how to select all the data corresponding to an id and display it in a table in laravel

I am currently developing an ATM application which shows certain work done, these elements are associated with a user id, what I need to show in my table is all the elements associated with the id of my ATM, as I am new to laravel I am not clear how to handle the query, Currently my DB fields are as follows

enter image description here

I need to show for example all the data associated with the usuario_id field that appears in the image.

the function that I am currently using and that brings me the data is the following where $respuestas is my variable to show them in my view.

function show($id) {
        $atm = Atm2::find($id);
        $respuestas = FormularioRespuesta2::whereAtmId($atm->id)->orderBy('id', 'asc')->get();
        $formulario = Formulario2::first();
        $respuesta = FormularioRespuesta2::whereAtmId($atm->id)->orderBy('id', 'desc')->first();
        $respuestas = $respuestas->where('atm_id', '=', $atm->id);
        return view('Administrador::atms2-show')->with(['atm' => $atm, 'formulario' => $formulario, 'respuesta' => $respuesta, 'respuestas' => $respuestas]);
    }

currently this function only brings me the last record and not the entire list items that the cashier has made.

enter image description here



via Chebli Mohamed

How to fetch all the data from a table minus the last element in laravel

I currently have a table where I need to review the details of an ATM but I do not need to view the last registered item

function show($id) {
        $atm = Atm2::find($id);
        $respuestas = FormularioRespuesta2::whereAtmId($atm->id)->orderBy('id', 'asc')->get();
        $formulario = Formulario2::first();
        $respuesta = FormularioRespuesta2::whereAtmId($atm->id)->orderBy('id', 'desc')->first();
        $respuestas = $respuestas->where('atm_id', '=', $atm->id);
        return view('Administrador::atms2-show')->with(['atm' => $atm, 'formulario' => $formulario, 'respuesta' => $respuesta, 'respuestas' => $respuestas]);
    }

the variable $respuestas is in charge of bringing the data I need, but currently I bring the last element linked to the cashier and I need to do the opposite.

I need you to only show me the data linked to the ATM, all except the last one entered.



via Chebli Mohamed

Trying to get property 'likes' of non-object (View: /app/resources/views/products/productView.blade.php)

on my local server this is working and on hosting (when I push it on heroku) it gives me an error. I dont know where I am doing this wrong

Trying to get property 'likes' of non-object (View: /app/resources/views/products/productView.blade.php)

Query

$findLikes = Comment::where('user_id', Auth::user()->id)->where('product_id', $id)->first();

View

@if((Auth::check()) && ($findLikes->likes == '1'))

    <a href="/unlike-product/" id="myNumber" name="likes" value="0" onclick="myFunction()"><i class="fa fa-heart-o"></i> UnLike</a> </small>

@elseif((Auth::check()) && ($findLikes->likes == '0'))

    <a href="/liked-product/" id="myNumber" name="likes" value="1" onclick="myFunction()"><i class="fa fa-heart-o"></i> Like it</a> </small>

@endif

THIS IS I WHAT TRIED NOW AND NOT RETURNING ANYTHING BUT LOADING THE PAGE

@if((Auth::check()) && $findLikes)
    @if($findLikes->likes == '1')
       <a href="/unlike-product/" id="myNumber" name="likes" value="0" onclick="myFunction()"><i class="fa fa-heart-o"></i> UnLike</a> </small>
    @else
       <a href="/liked-product/" id="myNumber" name="likes" value="1" onclick="myFunction()"><i class="fa fa-heart-o"></i> Like it</a> </small>
     @endif
@endif

UPDATED



via Chebli Mohamed

Problem with File Manager Package in Laravel

i'm using this Package alexusmai/laravel-file-manager which gave me a file manager, I integrated this package with TinyMCE 5.2.0

but I got a problem with image uploading

when I select an image from the file manager it doesn't appear in the editor...

Image when i upload it using file manager package



via Chebli Mohamed

Rest Api issue with Paytm gateway Laravel

I am developing my application with Laravel. Two projects are running one is for frontend and other one only for building APIs. But now I am facing complications while adding paytm payment gateway to it. Not able to understand how I could call the APIs while payment.

Anyone have any suggestions or any article which could help me to complete it.



via Chebli Mohamed

Cors issue when using laravel nginx

I have 2 applications api & front. I'm using laravel + nginx

server {
server_name api.website.com;
root /laravel/public;
listen 80;

error_page 401 403 404 500 502 503 504 /500.html;

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ ^/index\.php(/|$) {
    fastcgi_pass php;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_read_timeout 300;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS off;
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, HEAD, POST, PATCH, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Accept, Authorization, X-Requested-With, Application';
        return 204;
    }
}

client_max_body_size 64M;

error_log /var/log/nginx/wooxo_api_error.log;
access_log /var/log/nginx/wooxo_api_access.log;
}

server {
#listen 443 ssl http2;
listen 80;
root /laravel/angular/dist;
server_name app.website.com;
index index.html;

location ^~ / {
    try_files $uri /index.html;
    root /laravel/angular/dist/dist;
}

}

But I have the error : (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Can you help me please ? Have no idea. It seems to be a problem with headers. Thank you in advance and sorry for english.



via Chebli Mohamed

laravel cant send users name in related products

i use this code but i cant send users name in related products i use this code

  Creator: 

i cant show creator of products for productscontroller i use this:

public function index(){
        $products = Product::with(['users'])->get();
        return view('products.index', compact('products'));}

and for model product

public function users()
    {
        return $this->belongsTo(User::class);
    }

and for model user

public function products()
    {
        return $this->hasMany(Product::class);
    }

and table

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedInteger('user_id');
            $table->text('description');
            $table->integer('weight');
            $table->integer('price');
            $table->timestamps();
        });

this error see

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



via Chebli Mohamed

Trying to access array offset on value of type null (View: /app/resources/views/products/productView.blade.php)

can anyone help me with this error? my project is working fine on local server but when I push to heroku it gives me the below error. Any help ?

I am using php version 7.3.7 and laravel version 6.18.3 also I am using heroku for the first time. I have uploaded the code

**Product View**
@foreach($products as $p)
<section class="section single-wrap">
    <div class="container">
        <div class="page-title">
            <div class="row">
                <div class="col-sx-12 text-center">

                    <h3></h3>

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

        <div class="content-top">
            <div class="row">
                <div class="col-sx-6 col-sm-6">

                </div> 

<div class="col-sm-6 col-xs-12 cen-xs text-right">
                    <div class="bread">
                        <ol class="breadcrumb">
                          <li><a href="/">Home</a></li>
                          <li><a href="#">Shop</a></li>
                          <li class="active"></li>
                        </ol>
                    </div>
                </div>
            </div><!-- end row -->
        </div><!-- end content top -->

        <div class="row">
            <div id="singlewrapper" class="col-md-8">
                <div class="content nopad">
                    <div class="item-single-wrapper">
                        <div class="item-box">
                            <div class="item-media text-center">
                                <div id="slider" class="flexslider clearfix">

                                    <ul class="slides">
                                        <li><img src="" style="width:700px; height:400px;" alt="" class="img-responsive"></li>
                                    </ul>

                                </div>
                                <div id="carousel" class="flexslider clearfix">
                                    <ul class="slides">
                                        <li>
                                            @foreach (json_decode($p->filename) as $picture)
                                                <img src="" style="height:120px; width:200px"/>       
                                            @endforeach
                                        </li>
                                    </ul>
                                </div>  
                            </div><!-- end item-media -->

                            <div class="item-desc">
                                <b>Description</b>
                                <p>  </p>
                            </div><!-- end item-desc -->

                            <center>
                                <p>__________</p>
                            </center>

                            @if(count($comments)>0)
                                <div class="item-desc">
                                <b>Comments</b>
                                    @foreach($comments as $c)
                                        <p>  </p>
                                        
                                        <h6> by <b></b> at <b></b> </h6>  <br/>
                                    @endforeach
                                </div><!-- end item-desc -->
                            @else 
                                <div class="item-desc">
                                <b>Comments</b>
                                <p> No comments found </p>
                                </div><!-- end item-desc -->
                            @endif

                        </div><!-- end item-box -->


                    </div><!-- end item-single-wrapper -->
                </div><!-- end content -->
            </div><!-- end singlewrapper -->

            <div id="sidebar" class="col-md-4">
                <div class="boxes boxs">
                    <div class="item-price text-center">
                        <p>$</p>
                        <em><a href="#">Regular License</a></em>
                        <!-- <div class="rating">
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                        </div> -->
                        <hr>
                        <small> 
                        @if((Auth::check()) && ($findLikes == true))
                            <a href="/unlike-product/" id="myNumber" name="likes" value="0" onclick="myFunction()"><i class="fa fa-heart-o"></i> UnLike</a> </small>
                        @else
                            <a href="/liked-product/" id="myNumber" name="likes" value="1" onclick="myFunction()"><i class="fa fa-heart-o"></i> Like it</a> </small>
                        @endif
                        <hr>
                        <a href="/add-to-cart/" class="btn btn-primary">Add to Cart</a>

                        <button type="button" data-toggle="modal" data-target="#myModal">Comment</button></a>

                        <!-- Modal -->
                        <div class="modal fade" id="myModal" role="dialog">
                            <div class="modal-dialog">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Add your comments here <span class="fa fa-comment"></span></h4>
                                </div>
                                <div class="modal-body">
                                    <div class="login-form">
                                        <form method="post" action="/product-comment/">

                                        @csrf
                                            <div class="form-group">
                                                <input type="text" name="comment" required class="form-control" placeholder="comment here" />
                                            </div>

                                            <button type="submit" name="go" class="btn btn-primary">Add Comment</button>
                                        </form>
                                    </div><!-- end login-form -->
                                </div>
                                <!-- <div class="modal-footer">
                                <a href=""></a>
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Add Comment</button>
                             </div> -->
                            </div>

                        </div>
                    </div>

                        <ul class="list-inline social">
                            <li><a href="#"><i class="fa fa-facebook"></i></a></li>
                            <li><a href="#"><i class="fa fa-twitter"></i></a></li>
                            <li><a href="#"><i class="fa fa-google-plus"></i></a></li>
                            <li><a href="#"><i class="fa fa-dribbble"></i></a></li>
                            <li><a href="#"><i class="fa fa-behance"></i></a></li>
                            <li><a href="#"><i class="fa fa-pinterest"></i></a></li>
                        </ul>
                    </div><!-- end price -->
                </div><!-- end boxes -->

                <div class="boxes boxs">
                    <div class="desiger-details text-center">
                        <img src="upload/member_05.jpg" class="img-circle" alt=""></a>
                        <h4><a href="public-profile.html"></a></h4>
                        <small><a href="/follow-user/"><i class="fa fa-user-plus">
                        @if((Auth::check()) && ($findFollow == true))
                            </i> Unfollow</a> </small>
                        @else
                            </i> Follow </a> </small>
                        @endif
                    </div><!-- end designer -->
                </div><!-- end boxes -->

                <div class="boxes boxs">
                    <div class="item-details">
                        <table>
                            <tr>
                                <td>Created on:</td>
                                <td></td>
                            </tr>

                            <tr>
                                <td>Category</td>
                                <td></td>
                            </tr>

                            <tr>
                                <td>Followers:</td>
                                <td></td>
                            </tr>

                            <tr>
                                <td>Likes:</td>
                                <td></td>
                            </tr>

                            <tr>
                                <td>Comments:</td>
                                <td></td>
                            </tr>


                        </table>
                    </div><!-- end item-details -->
                </div><!-- end boxes -->
            </div><!-- end sidebar -->
        </div><!-- end row -->
    </div><!-- end container -->
</section>

@endforeach

<footer class="footer">
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-lg-5">
                <div class="media cen-xs">
                    <p>
                        &copy; Catalog INC. 2016 - All Rights Reserverd.<br>
                        Idea by <a class="madeby" href="http://showwp.com">Show WP</a> made with <i class="fa fa-heart"></i> coded with <i class="fa fa-html5"></i>
                    </p>
                </div>
            </div>
            <div class="col-md-6 col-lg-7">
                <ul class="list-inline text-right cen-xs">
                    <li><a href="#">Home</a></li>
                    <li><a href="#">Site Terms</a></li>
                    <li><a href="#">Copyrights</a></li>
                    <li><a href="#">License</a></li>
                    <li><a href="#">Legal</a></li>
                    <li><a class="topbutton" href="#">Back to top <i class="fa fa-angle-up"></i></a></li>
                </ul>
            </div>
        </div><!-- end row -->
    </div><!-- end container -->
</footer><!-- end footer -->
</div><!-- end wrapper -->
<!-- END SITE -->

<script src=""></script>
<script src=""></script>
<script src=""></script>
<!-- FlexSlider JavaScript
================================================== -->
<script src=""></script>
<script>
(function($) {
"use strict";
$(window).load(function() {
    $('#carousel').flexslider({
        animation: "slide",
        controlNav: false,
        directionNav: false,
        animationLoop: true,
        slideshow: true,
        itemWidth: 92,
        itemMargin: 0,
        asNavFor: '#slider'
    });

    $('#slider').flexslider({
        animation: "fade",
        controlNav: false,
        animationLoop: false,
        slideshow: true,
        sync: "#carousel"
    });
});
})(jQuery);
</script>


</body>
</html>`

Product Controller

public function showProductDescription($id) {

// echo $id;

$category = Category::all()->sortBy('category_name');
// $category->category_name;
$userLikes = new Comment();

$products = Product::where('id', $id)->get();
$comments = Comment::where('product_id', $id)->get();

$commentCount = Comment::where('product_id', $id)->get('comments')->count(); 
$pag = Comment::where('product_id', $id)->paginate(10);

if(Auth::check()) {
    $carts = Cart::where('user_id', Auth::user()->id)
                ->where('active', '=', '1')->count();

    $findFollow = Following::where('user_id', Auth::user()->id)
                    ->where('followed_to', $id)->first();

    $findLikes = Comment::where('user_id', Auth::user()->id)
                    ->where('product_id', $id)->first();


                    // dd(Product::all());
                    // dd($findFollow);
                    // dd($findLikes);
                    // dd($pag);
                    // dd($commentCount);
                    // die();

    return view('products.productView', compact('products', 'comments', 'pag', 'commentCount', 'carts', 'findFollow', 'category', 
                    'userLikes', 'findLikes'));

} else {
    $carts = Cart::where('active', '=', '1')->count();

    $findFollow = '';

    $findLikes = '';

                    // dd(Product::all());
                    // dd($findFollow);
                    // dd($findLikes);
                    // dd($pag);
                    // dd($commentCount);
                    // die();

    return view('products.productView', compact('products', 'comments', 'pag', 'commentCount', 'carts', 'findFollow', 'category', 
                                            'userLikes', 'findLikes'));
}


}

public function likedProduct($id) {

if(Auth::check()) {

    $product = Product::where('id', $id)->first();

    $userLikes = new Comment();
    $userLikes->user_id = Auth::user()->id;
    $userLikes->product_id = $product->id;
    $userLikes->likes = '1';

    $userLikes->save();

    if($product->total_likes == 0) {
        $product->total_likes = 1;
    } else {
        $product->total_likes = $product->total_likes + 1;
    }

    $product->save();
    return redirect()->action('ProductController@showProductDescription', ['id' => $id]);
} else {
    Session::flash("message", "OOPS! You dont have permission to upload the items. Please register first.");
    return redirect("/register-user");
}
}

public function unlikeProduct($id) {

if(Auth::check()) {
    $comments = Comment::where('user_id', Auth::user()->id)
                            ->where('product_id', $id)->delete();


    $product = Product::where('id', $id)->get('total_likes')->count();

    // echo $product;
    // die();

    if($product>0) {
        $productLikes = Product::where('id', $id)->first();
        $productLikes->total_likes = $productLikes->total_likes - 1;
        $productLikes->save();
    }

    // Session::flash("message", "OOPS! You dont have permission to upload the items. Please register first.");
    return redirect()->action('ProductController@showProductDescription', ['id' => $id]);
} else {
    Session::flash("message", "OOPS! You dont have permission to upload the items. Please register first.");
    return redirect("/register-user");
}


}
public function productComment($id) {
if(Auth::check()) {

    $c = Input::get('comment');

    $product = Product::where('id', $id)->first();

    $user_comments = new Comment();
    $user_comments->user_id = Auth::user()->id;
    $user_comments->product_id = $product->id;
    $user_comments->comments = $c;

    $user_comments->save();

    if($product->total_comments == 0) {
        $product->total_comments = 1;
    } else {
        $product->total_comments = $product->total_comments + 1;
    }

    $product->save();

    Session::flash('message', 'Your comment has been added successfully');
    return redirect()->action('ProductController@showProductDescription', ['id' => $id]);


}  else {
    Session::flash("message", "OOPS! You dont have permission to upload the items. Please register first.");
    return redirect("/register-user");
}     
}

I have updated the code so if you can help identifying the problem as I failed to identify the problem for the last one and half day and I need to get this fixed



via Chebli Mohamed

Laravel user roles ,Multi auth

I', trying to differentiate the user based on perspective role, i.e Admin, Supervisor, student etc. When admin or supervisor login it must go to their specific dashboard, and each user must not access other user's roles when one try access via ** URL * Im trying to do this using a single table USER adding additional field Role as type integer Below is my code for all related files.

Admin and Supervisor Middle ware code is same

namespace App\Http\Middleware;

use Closure;

class Admin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (! Auth::check()) { return redirect()->route('login'); }

if (Auth::user()->role == 1) {
    return redirect()->route('admin');
}
if (Auth::user()->role == 2) {
    return redirect()->route('supervisor');
}

}

}



via Chebli Mohamed

How to install vuexy (template or theme) in laravel?

I need to install a template admin panel vuexy. I do everything according to the steps, but php artisan not work. I don't know how install this.

https://pixinvent.com/demo/vuexy-html-bootstrap-admin-template/documentation/documentation-laravel.html



via Chebli Mohamed

Delete test in Laravel

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

I have this code:

  1. Controller
    public function destroy(Request $request)
        {
            if ($request->isMethod('post')) {
                foreach ($request->input('id') as $value) {
                    $this->model->delete($value);
                }
                return redirect()->route('ads.index')->with('success', 'Rekordy zostały usunięte!');
            }
        }
  1. Model
    class Ad extends Model
    {
        use ScopeActiveTrait;

        protected $quarded = ['id'];
        protected $fillable = ['company_id', 'user_id', 'title', 'content', 'provincial_id', 'enable', 'url_address'];
        public $timestamps = true;

        public function author()
        {
            return $this->belongsTo('App\Models\User', 'user_id');
        }
    }
  1. Test File
    public function testDeleteAd()
        {
            $this->withExceptionHandling();
            //$this->withoutExceptionHandling();
            $user = User::find(1);
            $this->be($user);

            $ad = factory(Ad::class)->create();
            //$this->post(route('ads.destroy'), ['id[]' => $ads->toArray(), '_token' => csrf_token()]);
            //$response = $this->call('POST', route('ads.destroy'), ['_token' => csrf_token(), 'id[]' => $ads->toArray(), 'id' => $ads->toArray()]); dd($response);
            //$this->assertDatabaseMissing('ads', ['id' => $ads->id]);

            $ad = Ad::where('id', $ad->id)->first();

            $response = $this->post(route('ads.destroy'), [
                'id' => $ad->id,
                '_token' => csrf_token()
            ]);
            $this->assertDatabaseMissing('ads', ['id' => $ad->id]);
        }

When I run this test, I have error:

root@142d1f3c30d0:/var/www# vendor/bin/phpunit --filter AdTest PHPUnit 9.0.1 by Sebastian Bergmann and contributors.

F 1 / 1 (100%)

Time: 1.83 seconds, Memory: 26.00 MB

There was 1 failure:

1) Tests\Feature\AdTest::testDeleteAd Failed asserting that a row in the table [ads] does not match the attributes { "id": 9 }.

Found similar results: [ { "id": 9, "company_id": 1, "user_id": 1, "title": "Dolore similique magnam tempora esse a ex ut excepturi.", "content": "Itaque animi fugit quod unde. Accusamus recusandae sit non quia cupiditate aspernatur. Sunt quas accusamus recusandae eius doloribus sequi.", "provincial_id": 2, "enable": "0", "url_address": "dolore-similique-magnam-tempora-esse-a-ex-ut-excepturi", "created_at": "2020-04-27 05:59:57", "updated_at": null } ].

/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:45 /var/www/tests/Feature/AdTest.php:71

How can I repair it? What's wrong?



via Chebli Mohamed

How to use Model in function parameter to reduce code in laravel?

This is how i am trying to update record in my laravel function which doesn't work

  public function completePacking(SaleOrder $saleOrder)
  {
    $saleOrder->update(['status' => 'Draft']);
  }

it is working

  public function completePacking($id)
  {
     $saleOrder = SaleOrder::findOrFail($id);
     $saleOrder->status = 'Dispatched';
     $saleOrder->save();
}

i want to use first method because it is less code but that is not working



via Chebli Mohamed

mergeBindings returns result from one match only

I am using mergeBindings to perform a subquery on Eloquent, but the result of the query is that is just give me result for one matching row. Hence all the rows shows the same value even if the ID in the where condition is specified.

$sub = Permissions::select('name');
...
->mergeBindings($sub->getQuery()->where("user_id",'=','rhc.id'))

Permissions holds information about user permissions (name and id). In the query I list all the permission ID`s for a specific user (SELECT rhc.id). But the result always gives me the same permission name no matter what the permission ID is. Example result:

user id: 1
permissions_id :1
name: "Admin"

user id: 1
permissions_id :2
name: "Admin"

user id: 1
permissions_id :3
name: "Admin"

I expect name to be NULL since they are not specified yet (ID 1 is "Admin", which is therefore correct).

Can this be done or does the subquery only take the result from the first match in the subquery and not for each row?

Thanks for any help!



via Chebli Mohamed

How manage classes in controller in laravel?

I am currently working on a project which is now expands too much so now every controller's top of project look like this.

use App\Helpers\Comments_Helper;
use App\Helpers\GetDeliveryRun_Helper;
use App\Helpers\Histories_Helper;
use App\Helpers\Notification_Helper;
use App\Helpers\Tables\TableHistory;
use Illuminate\Support\Facades\Queue;
use App\Helpers\Tables\TableManifest;
use App\Helpers\Tables\TableManifestConsignment;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Consignment;
use App\Models\Customer;
use App\Models\ConsignmentManifest;
use App\Models\Manifest;
use Auth;
use DB;
use File;
use Barryvdh\DomPDF\Facade as PDF;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Jobs\ManifestPOD\ConsignmentDownload;
use App\Jobs\ManifestPOD\ConsignmentZipper;
use Maatwebsite\Excel\Facades\Excel;
use Response;

is there any way to declare these classed globally and use it in every controller. what is best programming practice for this problem



via Chebli Mohamed

lundi 30 mars 2020

after update composer all vender files showing git

After apdate the composer in my laravel project 5k fies showing as a changes in git. how to ignore it. i already ignore vender repository in gitignore file. please help me to sort out this.enter image description here

gitignore code

/public/storage
/storage/*.key
/vendor
.env


via Chebli Mohamed

Laravel - Return only multiple relationships with records from controller or model

I'm returing a model with all the related models. My problem is that perhaps some models don't have records so they are returned in my $property variable as empty and I have to evaluate their existence in blade (not done yet) Is there any way in controller or parent model to return only the child relationships which have records? Or any blade directive to evaluate these cases? All relationships are 1:M.

Regards!

Controller Code

class PropertyController extends Controller
{
    public function details($id)
    {
        $property = Property::with('attributes', 'addons', 'distributions', 'images', 'attributes_2', 'services')
                    ->where('prop_id', $id)
                    ->first();
        // dd($property);
        return view('pages.processes.offerdemand.matchs.propertymodal', compact('property'));
    }
}


via Chebli Mohamed

Laravel Spatie Activity Log Ip Address Customize

I am using Laravel Spatie Activity Log package in my laravel application. I could customize in each module.

 public function tapActivity(Activity $activity, string $eventName)
 {
    $activity->description = "Category is {$eventName}. ";
    $activity->os = getOS();// custom hlper
 }

This problem was when I was going to save ip.

$activity->ip = $request->ip();

I think above field should be added. But where can we get $request ?



via Chebli Mohamed

Laravel concatenate src link with variables values

I need to dynamically complete google maps static URL with values from 2 variables.

The basic URL is:

<img src="http://maps.googleapis.com/maps/api/staticmap?center=LATITUDE,LONGITUD&zoom=12&size=400x400&key=APIKEY">

And I need to pass the following to variable to the URL replacing LATITUDE and LONGITUD:

{!! $property->prop_latitud !!}
{!! $property->prop_longitud !!

Can anyone can help me?

Regards



via Chebli Mohamed

Error ErrorException: Undefined index: id in Laravel test

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

I have this code:

class AdTest extends TestCase
{
public function testDeleteArticle()
    {
        $this->withoutExceptionHandling();
        $user = User::find(1);
        $this->be($user);

        $ads = factory(Ad::class)->create();
        $this->post('/ads-destroy', ['id' => $ads->id]);
        $this->assertDatabaseMissing('ads', ['id' => $ads->id]
    }
}

Record was add correct. Problem is wit delete.

I have error:

1) Tests\Feature\AdTest::testDeleteArticle
ErrorException: Undefined index: id
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

In application add/edit/remove works fine. Problem is only with this test.

My model:

class Ad extends Model
{
    use ScopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['company_id', 'user_id', 'title', 'content', 'provincial_id', 'enable', 'url_address'];
    public $timestamps = true;

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

My Controller:

public function destroy(Request $request)
    {
        if ($request->isMethod('post')) {
            foreach ($_POST['id'] as $value) {
                $this->model->delete($value);
            }
            return redirect()->route('ads.index')->with('success', 'Rekordy zostały usunięte!');
        }
    }

How can I repair this error?

Please help me :)



via Chebli Mohamed

Can't install Spatie Activity-log Package in Laravel 5.8

I was going to install spatie-activitylog package in my laravel application.

composer require spatie/laravel-activitylog

But I got this error.

 Problem 1
        - Conclusion: remove laravel/framework v5.8.37
        - Conclusion: don't install laravel/framework v5.8.37
        - spatie/laravel-activitylog 3.14.0 requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[7.x-dev], illuminate/support[6.x-dev, 7.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0
    .3, v6.0.4, v6.1.0, v6.10.0, v6.11.0, v6.12.0, v6.13.0, v6.13.1, v6.14.0, v6.15.0, v6.15.1, v6.16.0, v6.17.0, v6.17.1, v6.18.0, v6.18.1, v6.18.2, v6.18.3, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6
    .5.1, v6.5.2, v6.6.0, v6.6.1, v6.6.2, v6.7.0, v6.8.0, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.2.0, v7.2.1, v7.2.2, v7.3.0]
    .
        - spatie/laravel-activitylog 3.14.1 requires illuminate/support ^6.0|^7.0 -> satisfiable by laravel/framework[7.x-dev], illuminate/support[6.x-dev, 7.x-dev, v6.0.0, v6.0.1, v6.0.2, v6.0
    .3, v6.0.4, v6.1.0, v6.10.0, v6.11.0, v6.12.0, v6.13.0, v6.13.1, v6.14.0, v6.15.0, v6.15.1, v6.16.0, v6.17.0, v6.17.1, v6.18.0, v6.18.1, v6.18.2, v6.18.3, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6
    .5.1, v6.5.2, v6.6.0, v6.6.1, v6.6.2, v6.7.0, v6.8.0, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4, v7.0.5, v7.0.6, v7.0.7, v7.0.8, v7.1.0, v7.1.1, v7.1.2, v7.1.3, v7.2.0, v7.2.1, v7.2.2, v7.3.0]
    .
        - Can only install one of: laravel/framework[7.x-dev, v5.8.37].
        - don't install illuminate/support 6.x-dev|don't install laravel/framework v5.8.37
        - don't install illuminate/support 7.x-dev|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.0.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.0.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.0.2|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.0.3|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.0.4|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.1.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.10.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.11.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.12.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.13.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.13.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.14.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.15.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.15.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.16.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.17.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.17.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.18.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.18.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.18.2|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.18.3|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.2.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.3.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.4.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.5.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.5.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.5.2|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.6.0|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.6.1|don't install laravel/framework v5.8.37
        - don't install illuminate/support v6.6.2|don't install laravel/framework v5.8.37
        - don't install illuminat

e/support v6.7.0|don't install laravel/framework v5.8.37
    - don't install illuminate/support v6.8.0|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.0|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.1|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.2|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.3|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.4|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.5|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.6|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.7|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.0.8|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.1.0|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.1.1|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.1.2|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.1.3|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.2.0|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.2.1|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.2.2|don't install laravel/framework v5.8.37
    - don't install illuminate/support v7.3.0|don't install laravel/framework v5.8.37
    - Installation request for laravel/framework (locked at v5.8.37, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.37].
    - Installation request for spatie/laravel-activitylog ^3.14 -> satisfiable by spatie/laravel-activitylog[3.14.0, 3.14.1].

This package doesn't support laravel 5.8 anymore? I think Laravel 5.8 isn't so old. Should I use Laravel 7.0 which is latest version? Is there any version which supports laravel 5.8?



via Chebli Mohamed

How can i use scope in laravel query builder

I use laravel query builder instead Eloquent. Now, i have a lot of repeating joins. How can I use them without standard models scope in my query?

Simple:

public function getUserCourse(int $user_id)
{
return DB::table($this->table)
->select($this->table.'.id','title','description')
->join('user_course', $this->table.'.id','=','user_course.course_id')
->where('user_course.user_id','=',1)
->where('status','=', 0)
->get();
}


via Chebli Mohamed

SQLSTATE[42S22] error in Laravel 6 update function

I'm trying to run a update function in my laravel app but every time when i run the function it gives me this error,

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `apps` set `domain` = Testinput.test.com, `apps`.`updated_at` = 2020-03-30 13:18:32 where `id` is null)

Here is my update function in the controller,

public function update(Request $request,App $app, $id)
{
    $this->validate($request, [
        'domain' => ['required', 'string','min:2', 'max:255'],
    ],$request->all());

    $fullDomain = $request->domain;
    $app->domain=$fullDomain;
    $app = App::where('appId','=','1')->first()->update($request->all());
    return Redirect::back()->with('success',__('sentence.User updated successfully')); 
}

I dont't have a column called id in my apps table my column is appId



via Chebli Mohamed

Is there an alternative to laravel package zofe/rapyd?

I'm currently updating app from laravel 5.5 to version 7.3 and I have a problem with package zofe/rapyd wich is currently supporting only laravel versions to 5.6. Is there any alternative to this package that I can use ??? I searched the google all the way down but I didn't find anything usefull. Thanks for any help



via Chebli Mohamed

Laravel Spatie Get All Permissions with Eager Loading

everybody! I am using Laravel Spatie Permission Package. And I can get user's all assigned permissions like this.

$user->getAllPermissions()

However, I want to get all permissions with eager loading. Maybe like this.

$users = User::with('getAllPermissions')->get();

But this didn't worked.

I tried

$users = user::with('permissions')->get();

But query counts were same result with

$users = user::get();

So $user->getAllPermissions() is already eager loaded query?

Or is there any eager loaded query?



via Chebli Mohamed

dimanche 29 mars 2020

Laravel - Stop creating/updating laravel session for unauthorized users?

Laravel Version using - 5.4

In laravel when unauthorized user trying to login, a separate session is been created, I want to stop this session value creation and updation for unauthorized users

Ex - When a user trying to access https://www.example.com/login by providing wrong credentials in that case session value is been created and updated.

Session value will create/update for every request - In laravel all request pass through kernal.php Where StartSession is one middleware that is included globally.

app/Http/Kernal.php

/**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Session\Middleware\StartSession::class,
    ];

\Illuminate\Session\Middleware\StartSession::class - having one method.

/**
     * Start the session for the given request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Contracts\Session\Session
     */
    protected function startSession(Request $request)
    {
        return tap($this->getSession($request), function ($session) use ($request) {
            $session->setRequestOnHandler($request);

            $session->start();
        });
    }

which will create a session for every request. I would like to restrict the creation of a session in case of the unauthorized user who is trying "/login" URL & in case of forgot password or with invalid credentials.

Here, session driver, we are using as Redis server

SESSION_DRIVER=redis

As the session is been created for every request - Redis server memory utilization is getting consumed completely because of that I would like to restrict session creation / updation in case of forgot password or with invalid credentials.



via Chebli Mohamed

Failed to authenticate on SMTP server with username "*@gmail.com" using 3 possible authenticators

I tested this one line in my php artisan tinker in my prod VM

>>> Mail::raw('test mail from tinker', function ($message) {
...      $message->to('jdoe@gmail.com');
... });

I kept getting

Swift_TransportException with message 'Failed to authenticate on SMTP server with username "noreply.jdoe@gmail.com" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials l62sm6726934qte.52 - gsmtp
". Authenticator PLAIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials l62sm6726934qte.52 - gsmtp
". Authenticator XOAUTH2 returned Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials l62sm6726934qte.52 - gsmtp
".'
>>>

I have this in my .env

MAIL_ENCRYPTION=ssl
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_FROM=noreply.jdoe@gmail.com
MAIL_PASSWORD=qazwsx1234rfgvb
MAIL_TO=jane@outlook.com

That same qazwsx1234rfgvb is working on my local. I got email to sent out, and I see email.

I did this already :

  • ✅ Turn ON - Less Secure App
  • ✅ Turn ON - 2 Factor Authentication
  • ✅ Create App Password - qazwsx1234rfgvb is app word

Any suggestions on what elses to check ?



via Chebli Mohamed

Why PHP Artisan Tinker kept showing null?

┌──[root@jdoe]──[/home/jdoe/jdoe] 
└── cat .env | grep APP_URL
APP_URL=https://www.jdoe.com                                                                                                                     
┌──[root@jdoe]──[/home/jdoe/jdoe] 
└── php artisan tinker
Psy Shell v0.10.2 (PHP 7.3.11-0ubuntu0.19.10.3 — cli) by Justin Hileman
>>> env('APP_URL')
=> null
>>> env('APP_URL');
=> null
>>> 

I support to see https://www.jdoe.com

I can't explain this.



via Chebli Mohamed

How to insert and delete record in database which is using dynamic fields Laravel?

I am using Laravel 5. In this application, the staff name can be added and deleted dynamically. For creating new records, all functions run smoothly. However, I have some difficulties in updating the records. In 'edit' page, the staff names created are displayed and can be changed. These names can be updated. But, I put add button and delete button to enable user to add new staff name or delete existing staff name.

My function just can update existing record in database. But the new added staff name not inserted in database. This is my function to update in controller.

      public function update(Request $request, $id)
{

    $demo = Demo::findOrFail($id);

    $demo->tajuk_demo = $request->tajuk_demo;
    $demo->syarikat_id = $request->nama_syarikat;
    $demo->peralatan_sistem = $request->peralatan_sistem;
    $demo->tarikhmasa = $request->tarikhmasa;
    $demo->tarikhmasa_tamat = $request->tarikhmasa_tamat;
    $demo->tempat_demo = $request->tempat_demo;
    $demo->ulasan_demo = $request->ulasan_demo;
    $demo->komen_demo = $request->komen_demo;
    $demo->update();

    $pegawai = $request->all();

    // $rekod_id = $pegawai['rekod_id'];
    $itemRegistrationID = $pegawai['nama'];
    $OperasiID = $pegawai['pangkat'];
    $SectionID = $pegawai['bahagian'];

    $pegawai_semasa = Pegawai::where('rekod_id', '=', Input::get('rekod_id'))->exists();


        $peg_hadir = Pegawai::where('demo_id', '=', $id)
                 ->get();

        // Update the existing record
        foreach($peg_hadir as $peg){
        $key = array_search($peg->rekod_id, $pegawai['rekod_id']);
        $peg->itemRegistrationID = $itemRegistrationID[$key];
        $peg->OperasiID = $OperasiID[$key];
        $peg->SectionID = $SectionID[$key];
        $peg->save();
        }


    if (is_null($pegawai_semasa))
    {
        // Insert new record into database
        $count = count(Input::get('nama'));

        // get data
        $itemRegistrationID = Input::get('nama');
        $OperasiID = Input::get('pangkat');
        $SectionID = Input::get('bahagian');

        //loop through and save data
        for($i = 0; $i < $count; ++$i) {

            $pegawai = new Pegawai;
            $pegawai->demo_id = $id;
            $pegawai->itemRegistrationID = $itemRegistrationID[$i];
            $pegawai->OperasiID = $OperasiID[$i];
            $pegawai->SectionID = $SectionID[$i];
            $pegawai->save();
        }  
    }
    else
    {
      return redirect('demo');  
    }

}

This is the code in view blade for edit page:

<div class="form-group">
 <div class="row">
  <input type="button" class="add-row" value="Add">
  <button type="button" class="delete-row">Delete</button>
 </div>
</div>
<!--mula table  -->

<div class="form-group">
 <div class="row">
  <div class="col-lg-10">
    <table class="table table-striped table-bordered" id="pegawaihadir_table" >
      <thead>
        <tr>
          <td class="text-center col-lg-1"><strong>Pilih</strong></td>
          <td class="text-center col-lg-1"><strong>Pangkat</strong></td>
          <td class="text-center col-lg-3"><strong>Nama</strong></td>
          <td class="text-center col-lg-2"><strong>No Badan</strong></td>
          <td class="text-center col-lg-2"><strong>Seksyen</strong></td>
          <td class="text-center col-lg-2"><strong>No Tel</strong></td>
          <td class="text-center col-lg-2"><strong>Ext</strong></td>
        </tr>
      </thead>
        <tbody>

          @foreach($PegawaiHadir as $value)                                           
            <tr>
                <td><input type="checkbox" name="rekod" style="width:20px">
                  {!! Form::hidden('rekod_id[]', $value['rekod_id'], ['class' => 'form-control']) !!}
                </td>
                <td class="text-center"></td>
                <td>
                
                </td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
            </tr> 
          @endforeach                  
      </tbody>
    </table>              
 </div>
</div>

For dynamic fields, I am using js code to add and delete the record displayed in the page.

  <script>
count=1;
$(document).ready(function(){
    $(".add-row").click(function(){
        var markup = '<tr><td><input type="checkbox" name="rekod" style="width:20px"></td>';
        markup +=  '<td><input type="text" class="form-control pangkat"  name="pangkat[]" style="width:100px" readonly></td>';
        markup +=  '<td><select class="form-control select2 nama" name="nama[]" style="width:300px"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
        markup +=  '<td><input type="text" class="form-control no"  name="no[]" style="width:100px" readonly></td>';
        markup +=  '<td><input type="text" class="form-control bahagian" name="bahagian[]" style="width:100px" readonly></td>';
        markup +=  '<td><input type="text" class="form-control telefon" name="telefon[]" style="width:100px" readonly></td>';
        markup +=  '<td><input type="text" class="form-control ext" name="ext[]" style="width:100px" readonly></td></tr>';
        $("table tbody").append(markup);
        count++;

        });

    $(document).on('change', 'select.form-control.nama', function() {
        var PegID = jQuery(this).val();
        var row = $(this);
        // alert(PegID);
           if(PegID)
           {
              jQuery.ajax({
                 context: this,  
                 url : 'get_pegawai/'+PegID,
                 type : "GET",
                 dataType : "json",
                 success:function(data)
                 {
                    console.log(data);
                        $(this).closest('tr').find('td .form-control.pangkat').val(data.operasiname);
                        $(this).closest('tr').find('td .form-control.no').val(data.Nobadan);
                        $(this).closest('tr').find('td .form-control.bahagian').val(data.sectionname);
                        $(this).closest('tr').find('td .form-control.telefon').val(data.notelttp);
                        $(this).closest('tr').find('td .form-control.ext').val(data.ext);  
                 }
              });
           }
           else
           {
              $(this).closest('tr').find('td .form-control.pangkat').empty();
              $(this).closest('tr').find('td .form-control.no').empty();
              $(this).closest('tr').find('td .form-control.bahagian').empty();
              $(this).closest('tr').find('td .form-control.telefon').empty();
              $(this).closest('tr').find('td .form-control.ext').empty();  
           }

    });


    // Find and remove selected table rows
    $(".delete-row").click(function(){
        $("table tbody").find('input[name="rekod"]').each(function(){
            if($(this).is(":checked")){
                $(this).parents("tr").remove();
            }
        });


    });



});    
</script>

I also doesn't know how to identify the selected staff name to be deleted from existing record in database. I am providing a complete code to ease anyone who want to help to understand better. Thank you.



via Chebli Mohamed

Contact Form With Google reCaptcha - Laravel 7

I have a form and Google Captcha in Laravel 7

enter image description here

I already include

use Request;

I still get this error after submitting my form

message: "Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, instance of Illuminate\Support\Facades\Request given,

If I tried include

use Illuminate\Http\Request;

I will get

Class App\Http\Controllers\Request does not exist


This is what I have

public function store(Request $request)
{

    $inputs           = Request::all();
    $name             = str_replace('SELECT', '', $inputs['name']);
    $message          = str_replace('SELECT', '', $inputs['message']);
    $email            = str_replace('SELECT', '', $inputs['email']);

    $this->validate($request, [
        'name'    => 'required|max:255',
        'email'   => 'required|email',
        'message' => 'required',
        'captcha' => 'required|captcha',
    ]);

    $contact          = new Contact;
    $contact->name    = str_replace('*', '',$name);
    $contact->message = str_replace('*', '',$message);
    $contact->subject = str_replace('*', '',$message);
    $contact->email   = str_replace('*', '',$email);
    $contact->save();

    // dd($contact,$inputs);

    $mail = Mail::send('layouts.share.emails.contact', array(
        'message' => $message,
        'input' => $inputs
    ) , function ($message)
    {
        $message->from(env('MAIL_FROM') , 'www.jdoe.com');
        if(env('APP_ENV') == 'local'){
            $message->to(env('MAIL_TO') , 'John Doe')->subject(' Contact from '.env('APP_URL'));
        } else {
            $message->to(env('MAIL_TO') , 'John Doe')->subject(' Contact from www.jdoe.com ');
        }

    });

    return $contact;


}

How do I fix that ?

  • Should I use pass all my $inputs into it ?
  • How should I properly use the validate functions with the Google Captcha ?


via Chebli Mohamed

add data using laravel and vue.js

good day; i new in laravel with vue.js i have simple two questions:- 1- when i want to store email in data base but when i send it using axios request email sent as empty field when i get response from validation that email is required that mean data sent empty 2- i want when data stored successfully i want to show message wthis response and disappear after 3 second other wise show validation error this is my code
my vue.js code

<template>
    <div>
        <!-- ===== start footer ===== -->
        <footer>
            <div class="container">
                <div class="box-form-footer">
                    <div class="boximg-form">
                        <img src="/images/service/message.png" alt="">
                    </div>
                    <div class="row">
                        <div class="col-md-3 col-sm-12">
                            <div class="box-title">
                                <h3> اشترك في النشرة الاخبارية
                                </h3>
                            </div>
                        </div>  

                        <div class="col-md-6 col-sm-12">
                            <div class="box-title">
                                <input v-model="email"  name="email" type="text" placeholder="ضع بريدك الالكتروني">
                            </div>
                        </div>
                        <div class="col-md-3 col-sm-12">
                            <div class="box-title">
                                <button @click="subscribe()"> اشترك</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-4 col-md-6">
                        <div class="logo-footer">
                            <img :src="`upload/${footerData[0].logo}`" alt="">
                            <p>
                            
                            </p>
                        </div>
                    </div>
                    <div class="col-lg-4 col-md-6">
                        <div class="box-links">
                            <h3>اقسام الموقع </h3>
                            <ul>
                                <li><a href="index.html"><i class="fas fa-chevron-left"></i> الرئيسية</a></li>
                                <li><a href="about-us.html"><i class="fas fa-chevron-left"></i> عن KDL </a></li>
                                <li><a href="service.html"><i class="fas fa-chevron-left"></i> خدماتنا اللوجستية</a></li>
                                <li><a href="order-service.html"><i class="fas fa-chevron-left"></i> طلب خدمة</a></li>
                                <li><a href="careers.html"><i class="fas fa-chevron-left"></i> الوظائف </a></li>
                                <li><a href="branches.html"><i class="fas fa-chevron-left"></i> فروع KDL </a></li>
                                <li><a href="contact-us.html"><i class="fas fa-chevron-left"></i> اتصل بنا</a></li>

                            </ul>
                        </div>
                    </div>
                    <div class="col-lg-4 col-md-6">
                        <div class="box-cont">
                            <h3>تواصل معنا</h3>

                            <div class="box-location-new">
                                <ul>

                                    <li class=".lii"><i class="fa fa-phone fa-fw"></i>  </li>
                                    <li class=".lii"><i class="far fa-envelope-open"></i></li>
                                    <li class=".lii"><i class="fa  fa-map-marker fa-fw"></i> </li>

                                </ul>
                            </div>
                            <ul class="soch">


                                <li><a :href="footerData[0].facebook"> <i class="fab fa-facebook-f"></i></a></li>
                                <li><a :href="footerData[0].instagram"> <i class="fab fa-instagram"></i> </a></li>
                                <li><a :href="footerData[0].twitter"> <i class="fab fa-twitter"></i></a></li>
                                <li><a :href="footerData[0].youtube"> <i class="fab fa-youtube"></i></a></li>

                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <!-- <div class="overlay"></div> -->
        </footer>
        <!-- ===== end footer ===== -->

        <!-- =====start copy===== -->
        <div class="copy">
            Copyright 2018 
        </div>
        <!-- =====end copy===== -->
    </div>
</template>

    <script>
        export default {

            name: "myFooter",
            data: function () {
                return {
                    footerData:{},
                    errors:{},
                    email:'',
                    message:'',
                    status:''
                }
            },
            mounted(){
                axios.post('/websiteSetting')
                    .then((response) =>{
                        this.footerData=response.data
                    }).catch((error) =>this.errors=error.response.data.errors )
            },
            methods:{
                subscribe:function () {
                    axios.post('/subscribeMe',this.email)
                        .then((response) =>{
                            if(this.status=='success'){
                                this.message='ok';
                            }else{
                                this.message='failed';
                            }
                            }).catch((error) =>this.errors=error.response.data.errors )

                }
            }


        }
    </script>

my controller is

class SubscribeController extends Controller
{

    //start add email for subscribe user
    public function subscribeMe(Request $request )
    {
        //prepare data for validation


        $validationarray=Validator::make($request->all(),
            [
                'email' => ['required', 'string', 'email', 'max:255', 'unique:subscribes'],
            ],[],[
                'email' => 'Email',
            ]);

        if($validationarray->fails())
        {
            foreach ($validationarray ->messages()->getMessages() as $field_name =>$message):
                $response['message']=$message;
                $response['message1']=$request->email;
            endforeach;
            $response['status']="failed";
            return response()->json($response);
        }
        // start pass data to model
        $data=array(
            'email'     =>$request->email,
        );

        // start add data
        $add=Subscribe::create($data)->id;
        if(false !=$add)
        {
            return response(['status'=>'success',"message"=>"Your Email Added Successfully"]);

        }else{
            return response(['status'=>'failed',"message"=>"Error Adding data please try again !!"]);

        }

    }

}

my route is

Route::post('/subscribeMe', 'SubscribeController@subscribeMe');



via Chebli Mohamed

How extend cms on laravel? All Commands don't work

Cms from codecanyon. So it's installing through form, as many other cms. I want to extend it, but when after the installation, I connect via ssh to my project which created in Laravel, no command works (php artisan ... - there's no file or detective with this name). Even composer didn't install when I install this cms, so please help me how to extend it? P.S. Sorry for my English.. In two words:: I want to do so all commands that I can do in localhost where installed laravel via composer, worked with this cms, it's all what I want... Please help me



via Chebli Mohamed

Get all the products which are inside parent Category and child categories in Laravel with the help of relation

I have category and product table as follows:

Categories:

id | name | slug | parent_id

Products :

id | brand_id | name | slug | price | desc

Product_categories :

id | category_id | product_id

Product Model:

<?php

namespace App\Models;
use App\User;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * @var string
     */
    protected $table = 'products';

    /**
     * @var array
     */
    protected $fillable = [
        'brand_id', 'sku', 'name', 'slug', 'description', 'quantity',
        'weight', 'price', 'sale_price', 'status', 'featured',
    ];

    /**
     * @var array
     */
    protected $casts = [
        'quantity'  =>  'integer',
        'brand_id'  =>  'integer',
        'status'    =>  'boolean',
        'featured'  =>  'boolean'
    ];

     /**
     * @param $value
     */
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = Str::slug($value);
    }

    public function categories()
    {
    return $this->belongsToMany(Category::class, 'product_categories', 'product_id', 'category_id');
    }

    public function product_attributes()
    {
    return  $this->belongsToMany(Attribute::class, 'product_attributes')->withPivot('value', 'quantity');
    }

    public function users()
    {
    return $this->belongsToMany(User::class,'wishlists');
    }

}

Category Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use TypiCMS\NestableTrait;
use Illuminate\Support\Str;


class Category extends Model
{
    use NestableTrait;
    protected $table = 'categories';

    protected $fillable = [
        'name', 'slug', 'description', 'parent_id', 'featured', 'menu', 'image',
    ];

    protected $casts = [
        'parent_id' => 'integer',
        'featured' => 'boolean',
        'menu' => 'boolean',
    ];

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = str_slug($value);
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }


    public function products()
    {
    return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
    }
 }

I'm getting products related to specific category :

http://localhost:8000/category/kurta-sets

Now i'm getting all kurta sets, but i also want to get all products when i pass slug of parent category for eg: if i pass http://localhost:8000/category/top-wear then i should get all products which are in Shirts, Jackets, T-shirt.

enter image description here

I'm getting all child categories in my controller with following code:

public function show($slug)
    {
        $category = $this->categoryRepository->findBySlug($slug);
        $child_categories=$this->categoryRepository->getChildCategories($category->id); 
        dd($child_categories->children);  //return all child categories which are inside parent category
        return view('site.pages.category', compact('category','child_categories'));
    }


via Chebli Mohamed

Laravel: Calling paginate() inside a blade?

I have access to a collection called $files inside my blade. I am paginating and setting it to $allFiles.

<?php $allFiles = $files->paginate(12); ?>

In the blade beneath that, when I call:

<div>
   
</div>

, I am getting the error call to a member function links() on array. I am not sure what I am doing wrong.



via Chebli Mohamed

samedi 28 mars 2020

Sorry, your session has expired. Please refresh and try again

I have a site http://142.93.112.185/ written in Laravel 5.8 When you double click on my name, a sign-in form will come up

enter image description here

does not matter what I put into the form, after submit I kept getting this.

enter image description here

What cause this ? I've tried to put dd("HERE") in my controller, I can't even get it to display.

public function postSignIn()
{

    dd("HERE");
    ...
}

Any hints for me ?


HTML

<form action="/" method="POST" name="signinForm">
    {!! csrf_field() !!}

    <p style="color: red;" ng-show="signinForm.username.$invalid && signinForm.username.$touched"> Invalid Email/Username
    </p>

    <div class="form-group">
        <label for="username">Email</label>
        <input type="email" class="form-control"  id="username" name="username" placeholder="Enter Username" ng-model="username" ng-required="true"
        >
    </div>


    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" autocomplete="off"
        ng-model="password" ng-required="true"
        >
    </div>

    <div class="login-buttons"  >
        <button type="submit" class="btn btn-primary btn-block " ng-disabled="signinForm.username.$invalid || signinForm.password.$invalid">Log in</button>
    </div>

</form>


via Chebli Mohamed

Laravel 5 : Where can I find the source code of the validation rules?

I am using Laravel 5.2 for my project. Now I need a validation rule namely "after_or_equal" which was introduced in 5.4. So my aim is to clone (or get inspired by it) this rule as it does not exist in 5.2 (I want to implement it as described in the doc).

However I searched Laravel's git repository for this rule but could only find its corresponding error message in English.

So where can I find how they wrote the rule for "after_or_equal" ?

Any help appreciated :-)



via Chebli Mohamed

i need code to download pdf (mediumblob) from database (phpmyadmin) in laravel

1.web.php:

Route::get('/', function () { $users = DB::table('products')->select('id_products','name_products','image_products' )->get(); return view('metrial', compact('users')); }); Route::get('metrial','AuthController@test');

2.metrial.blade.php:

<div class="container">
  <div class="row">
  @foreach ($users as $user)

<div class="col-4">
<div class="card" style="width: 18rem;margin:10px; box-shadow:5px 5px 5px 5px #7ed6df;">
<img src="data:image/png;base64," class="card-img-top" > 
  <div class="card-body">
  <h5 class="card-title"></h5>
    <h6 class="card-subtitle mb-2 text-muted"></h6>
    <p class="card-text"></p>
     </div>
</div>
    </div>
    @endforeach
  </div>
</div>

** my tabel (products): (id_products :INT , name_products: varchar(255), describ_products: text , image_products :blob, sheet_products :mediumblob )**



via Chebli Mohamed

Dynamic seeding in laravel 5.4

I'm extremely new to laravel and having trouble with this seeder. I feel like it should be an easy thing to do, I just don't have the right tools for it yet.

I need to populate a column with data based on a different column. More specifically, I want to take the employee_id, find where their location is in the employee table, and populate that id in the application table. This is what I have so far:


use Illuminate\Database\Seeder;

use App\Employee;
use App\Application;


class ApplicationEmployeeLocationTableSeeder extends Seeder 
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $applications= Application::all();

        foreach ($applications as $application)
        {
            $location_id = Employee::whereId($application->employee_id)->pluck('location_id')->first();
        }

    }

}

This returns all the ids I'm looking for as a string, but how do I put these values into location_idin the applications table? Running this seeder doesn't produce an error, but it doesn't do anything either.

Let me know if there's any other information you need, and thanks in advance.



via Chebli Mohamed

'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER' in aws ec2 windows server

Hi trying to host a Laravel 5.4 php web site in aws ec2 windows server-(http://3.133.59.5/) and also using bitnami-7.3 run Laravel project.I'm getting following error when run the error

Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'

i tried change the config/database.php and add

            'modes'  => [
            'ONLY_FULL_GROUP_BY',
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_ENGINE_SUBSTITUTION',
        ],

but it didn't fix the this issue



via Chebli Mohamed

Is Laravel 5.5.48 compatible with php 7.1 and xampp version((7.1.2) or(v3.2.2))?

  • Checking laravel compatibility
  • To know if it works with xampp 7.1.1 and php 7.1


via Chebli Mohamed

vendredi 27 mars 2020

Image not displaying in view. from database

In my laravel project I tried to load images from database. But it displays the broken link. But when I inspect the image it shows the link. But when i clicked the link it shows 404 error..... this is my codes

this is the code of view .............

@extends('layouts.app')

@section('content')
<div class="d-flex justify-content-end">
    <a href="" class="btn btn-success mb-2">Add Posts</a>
</div>

<div class="card card-default">
    <div class="card-header">Posts</div>

    <div class="card-body">
        <table class="table">
            <thead>
                <th>Image</th>
                <th>Title</th>
            </thead>
            <tbody>
                @foreach ($posts as $post)
                    <tr>
                        <td><img src=""></td>
                        <td></td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>
@endsection

.............

and this is the code of controller

public function store(CreatePostsRequest $request)
{
    //Upload the image

    $image = $request->image->store('public/img');
    //create the post
    Post::create([
        'title' => $request->title,
        'description' => $request->description,
        'content' => $request->content,
        'image' => $image
    ]);
    //flash a message with seasson

    session()->flash('success','Post created successfully');
    //redirect user

    return redirect(route('posts.index'));


}

and i linked the storage to the public folder. But still its not working



via Chebli Mohamed

Laravel-sitemap set priority depends on depth

Is there any way to set priority depends on depth?

I hope More depth paths go, less priority would be taken.

SitemapGenerator::create($url)
    ->getSitemap()
    ->writeToFile(public_path('sitemap.xml'));


via Chebli Mohamed

Group pages in DOMPDF

I'm looking for an idea to group pages, or to put pages numbering into sets.

So, for example, if I have 15 pages, I want to group them as follows: first set of pages to be displayed as 1/7, 2/7... 7/7; second set to be displayed like 1/2, 2/2; third 1/3, 2/3, 3/3 and final set to be like 1/3, 2/3, 3/3. I have dynamic data, so the sets and number of pages may vary. Is this possible to do with DOMPDF?

So far, here's what I have in Laravel controller:

    $pdf = PDF::loadView('template', ["buzz" => $buzz, "foo" => $foo]);
    $dom_pdf = $pdf->getDomPDF();
    $canvas = $dom_pdf->get_canvas();
    $canvas->page_text(260, 800, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));
    return $pdf->stream('document.pdf');

Thanks in advance



via Chebli Mohamed

Laravel creating a pop-up form to create and edit

I am new to Laravel. currently, I am creating a website to show the information of the data, In that page, I hope to make it to pop-up a form to let the user create and also edit the data. But I have no idea about the pop-up form. Anyone can give me some advice? The edit will be beside each of the data and create will be at the bottom of the UI. I already do the controller for the update function. Any idea about it?

HERE IS MY CODE OF INDEX

@section('content')

<div class="panel-body">
  @if(count($areas)>0)
  <table class="table table-striped task-table">
      <thead>
        <tr>
          <th>No.</th>
          <th>Area Name </th>
        </tr>
      </thead>
      <tbody>
        <div class="form-popup" id="myForm">
        @foreach( $areas as $i => $area)
        <tr>
          <td class="table-text">
            <div></div>
          </td>
          <td class="table-text">
            <div></div>
          </td>
          <td class="table-text" >
            <button>edit</button>
          </td>
        </tr>
        @endforeach
      </tbody>
  </table>
  @endif
@endsection

IDK how can I create the form for the edit function. Any suggestion will grateful.



via Chebli Mohamed

Upload PDF file with laravel and vuejs

i try to upload a pdf file and insert it to DB in my project using laravel+vuejs but 405 error shown 405 (Method Not Allowed) any help guys ?? this is ProjectDetail.vue:

       <form @submit="formSubmit" enctype="multipart/form-data">
         <input type="file" name="file" v-on:change="onFileChange">
         <button class="btn btn-success">Submit</button>
       </form>
              onFileChange(e){
            console.log(e.target.files[0]);
            this.file = e.target.files[0];
        },
        formSubmit(e) {
            e.preventDefault();
            let currentObj = this;

            const config = {
                headers: { 'content-type': 'multipart/form-data' }
            }

            let formData = new FormData();
            formData.append('file', this.file);

            axios.post('api/formSubmit/'+this.key, formData, config)
            .then(function (response) {
                currentObj.success = response.data.success;
            })
            .catch(function (error) {
                currentObj.output = error;
            });
        },

and this is route :

Route::post('/formSubmit/{id}','API\FileController@formSubmit');

and this id my controller:

 public function formSubmit(Request $request,$id)
{
    $fileName = time().'.'.$request->file->getClientOriginalExtension();
    $request->file->move(public_path('upload'), $fileName);
    $project =Projet::where('id',$id)->first();
    $project->file= $request->file;
    return response()->json(['success'=>'You have successfully upload file.']);
}

}



via Chebli Mohamed

Log ERRORs html form post to external url

My API brings the client to my domain, this API request contains a parameter called return_url, where after process is complete on my domain we will post on client's return_url along with response parameter.

To do this, redirect to return_url, I have code as following:

<form action="http://client-return-url.com" method="post" name='returnform'>
    <input type="hidden" name="request_id">
    <input type="hidden" name="status">
</form>
<script>
    window.onload = function(){
      document.forms['returnform'].submit();
    }
</script>

This works fine.

Is there a way I can save a log if there is error, for example the return url is incorrect URL that doesn't exist, or there is a 500 error due to some code issue on return_url.

Again, return_url is not in my control, the moment I do a form post control is away from me, but I want to inform my clients of any error when I do form post on their return_url.

Thanks,

K



via Chebli Mohamed

force encoding to work on request made for laravel api by web browser

I am maintaning an API that have some requests made by a front-end app. When I call it from postman, all work well, including its encoding. The response is:

{ "message": "Esse nome de usuário está disponível" }

However, when I make it from browser, I receive:

{"message":"Esse nome de usu\u00e1rio est\u00e1 dispon\u00edvel"}

I already made this tutorial, that creates an middleware forcing the encoding, and on my project I set it like this, unlike the code it sugests:

$request->headers->set('Accept', 'application/json; charset=UTF-8');
$request->headers->set('Charset', 'utf-8');

In postman, I saw that these headers were not setted in the response of the request.

Also, I already tried to set in my controller response:

return response()->json([
                'message' => __('auth.nickname_available'), 
            ], 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8']);

I followed this tip. But neither worked.

How can I can make this work well?



via Chebli Mohamed

Using MPDF version 6.0

Previously i used mpdf version 8.6.For that i used laravel framework 5.4, Top of controller

use mPDF\mPdf;

In Controller constructor,

 $mpdf = new mpdf(['tempDir' => __DIR__ . '/custom/temp/dir/path']);

In function used

 $mpdf = new mpdf();                   

  $mpdf->SetHTMLHeader($this->header($data),'1', true);

  $mpdf->SetHTMLFooter($this->footer());

  $mpdf->AddPage('p','','','','',10,10,37,20,10,10);

   $mpdf->WriteHTML($html);

   $mpdf->Output();

Due to my server version 5.6 i have to use mpdf 6.1.0 version. For that version using the same code i get error



via Chebli Mohamed

Property or method is not defined on the instance but referenced during render while passing data from Laravel to Vue

I tried to pass data(or variable) from Laravel controller to Vue component via blade but i faced this error.

app.js

Vue.component('vue-home', require('./components/HelloWorld.vue').default);

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

My controller

        $slider = DB::table('sliders')->orderBy('place')->get();

        return view('main/index',compact('slider'));

index.blade.php

<!-- /resources/views/main/index.blade.php -->
@extends('layouts.app')
@section('content')
    <div id="app">
        
        <vue-home slider=""></vue-home>
    </div>
@endsection

HelloWorld component script

<script>
    export default {
        name: 'HelloWorld',
        props: ['slider'],

        data: function () {
            return {
                slider:this.slider,
            }
        },
        mounted(){
            console.log(this.slider)
        }
    }
</script>

But nothing shown in my page besides design and i want to pass my data . How can i achieve that?
Btw , Vue dev tools say that VueHome has attrs and i can see data in here .



via Chebli Mohamed

Laravel Bootstrap Modal - Show modal on click event with AJAX call data

I have been reading many questions and I didn't find a clear example on how to popup a bootstrap modal for each record in a table. Click event on a button for each record will popup a bootsrtap modal and fill it with data that comes from an AJAX get request to laravel. Each record can have different modals, so I believe also it's necessary to set a unique id attribute for each row. Frontend and backend is developed in laravel.

Is there any basic example as a starter?

Regards



via Chebli Mohamed

How to download file when function in queue in laravel?

I have two function first get files and second make zip file and download it. I make jobs for both of these functions queue is working correct. it is making zip file not downloading it. i think because it is in queue . here i am posting second function which is in queue

queue

 Consignment::withChain([
      new ConsignmentDownload($id)
  ])->dispatch($id);

in ConsignmentDownload here is function consignmentDownload

 public static function consignmentDownload($id)
  {

    $manifestId = $id;
    $manifests =  Manifest::find($manifestId);
    $zipper = new \Chumper\Zipper\Zipper;

    $path = public_path('manifest_pdfs/manifest_' . $manifestId);

    foreach ($manifests->consignments as $allConsignment) {

      $filepath = $path . '/cosignment_' . $allConsignment->id . '_pod.pdf';

      //add/create pdf zip 
      $zipper->make($path . '/manifest_' . $manifestId. '.zip')->add($filepath);
    }

    $zipper->close();


    return response()->download($path . '/manifest_' . $manifestId . '.zip');

  }

return response()->download is not working i want to download that zip file.



via Chebli Mohamed

can't add user photo with vuejs

i have built a profile components to my projects (laravel+vuejs) when i try to show the user photo in her place it didn't show i try many ways but no solution .when i check the DB i find it but there is a problem that i can find it..Any help guys??? this the code belongs to how i want to sow the user photo:

       <div class="row">
      <div class="col-md-3"  v-for="user in users"  v-if=" user.id == key "  :key="user.id">


        <!-- Profile Image -->
        <div class="card card-primary card-outline"  >
          <div class="card-body box-profile">
            <div class="text-center">
              <img class="profile-user-img img-fluid img-circle" :src="getProfilePhoto()" 
               alt="User profile picture" >
            </div>

and this the main script :

<div class="form-group row">
                                <label for="photo" class="col-sm-3 col-form-label">Profile Picture</label>
                          <div class="col-sm-10">
                                    <input type="file"  name="photo"  @change="updateProfile" class="form-input">
                                </div>

                            </div>

                  <div class="form-group row">
                    <div class="col-sm-10">
                      <button   @click.prevent="updateInfo"  type="submit" class="btn btn-danger">Submit</button>
                    </div>
                  </div>
                </form></div>
              </div>
              <!-- /.tab-pane -->
            </div>
            <!-- /.tab-content -->
          </div><!-- /.card-body -->
        </div>
        <!-- /.nav-tabs-custom -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  <!-- /.container-fluid -->
   <!-- /.content -->
         </div>

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


  </template>

    <script>
export default {
    data(){
     return{
    form : new Form({
    location:'',
    eucation:'',
    photo:'',
    skills:'',
    email:'',
    password:''

   }),

         key : this.$route.params.id,
          users:[],
            roles:{},
            role:{
                id:'',
              role:''
            },
            user:{

            },

     }
    },
    methods:{
          afficherMembre(){
               axios.get('/api/membre').then(({ data }) =>(this.users = data.data));
          },
         getProfilePhoto(){

            let photo = (this.form.photo.length > 200) ? this.form.photo : "/img/profile/"+ 
        this.form.photo ;
            return photo;
        },

        updateInfo(){
        this.form.put('/api/profile')
            .then(()=>{
                this.form.reset();                 })
            .catch(() => {
                               });
        },
        updateProfile(e){
            let file = e.target.files[0];
            let reader = new FileReader();

            let limit = 1024 * 1024 * 2;
            if(file['size'] > limit){
                swal({
                    type: 'error',
                    title: 'Oops...',
                    text: 'You are uploading a large file',
                })
                return false;
            }

            reader.onloadend = (file) => {
                this.form.photo = reader.result;
            }
            reader.readAsDataURL(file);
        },
        afficherProjet(){
        axios.get("/api/getProjectsUserConnecte").then(({ data }) => (this.projets = data));
        },
    },


created(){
   this.afficherMembre();
},
    mounted() {
        console.log('Component mounted.')
    }


  }


via Chebli Mohamed