mardi 29 décembre 2015

deleting specific record from the database in laravel

hi everyone i'm trying to make a simple delete function in my code , this is my controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Auth;
use App\User;
use App\Product;
use DB;

class listController extends Controller
{
    //
    public function getIndex(){

        $list=DB::table('wishlist')->get(['id','product_id','user_id']);
        $product=Product::get(['name','id','salary','image_name']);
        $user=DB::table('users')->get(['id']);
        return view('contents.wishlist')->with('list',$list)
                                        ->with('product',$product)
                                        ->with('user',$user);
    }
    public function postIndex(Request $request){
        $id=$request->input('id');
        $user_id=Auth::user()->id;
        $product_id=Input::get('product_id');


        DB::table('wishlist')->insert(['id'=>$id,'user_id'=>$user_id,'product_id'=>$product_id]);
        return redirect()->action('listController@postCreate');
    }
    public function deleteProduct(Request $request,$id){
        $pro=$request->get('id');
        DB::table('wishlist')->where('id',$pro)->delete();
        return redirect('wishlist/'.$pro);
    }
}

and my view is like that :

@extends('master')
@section('content')

<div class="wrapper-breadcrums">
    <div class="container">
        <div class="row">
            <div class="col-sm-24">
                <div class="breadcrumbs">
                    <ul>
                        <li class="home"> <a href="http://localhost/shopsite/public/home" title="Go to Home Page"><span >Home</span></a> <span class="separator">/ </span>
                        </li>
                        <li class="cms_page"> <strong>My Account</strong>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div><!-- /.wrapper-breadcrums -->

<div class="em-wrapper-main">
    <div class="container container-main">
        <div class="em-inner-main">
            <div class="em-wrapper-area02"></div>
            <div class="em-main-container em-col2-left-layout">
                <div class="row">
                    <div class="col-sm-18 col-sm-push-6 em-col-main">
                        <div class="em-wrapper-area03"></div>
                        <div class="my-account">
                            <div class="my-wishlist">
                                <div class="page-title title-buttons">
                                    <h1>My Wishlist</h1>
                                </div>
                                    <fieldset>

                                        <table class="data-table" id="wishlist-table">
                                            <thead>
                                                <tr>
                                                    <th></th>
                                                    <th>Product Details and Comment</th>
                                                    <th>Add to Cart</th>
                                                    <th></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($product as $p)
                                                @foreach($list as $l)
                                                @if($p->id == $l->product_id)
                                                @if($l->user_id == Auth::user()->id)
                                                <tr id="item_6">
                                                    <td>
                                                        <a class="product-image" href="product_detail" title=" {{$p->name}} "> <img src="{{asset('images/')}}/{{$p->image_name}}" width="113" height="113" alt=" {{$p->name}} " /> </a>
                                                    </td>
                                                    <td>

                                                        <h3 class="product-name"><a href="product_detail" title=" {{$p->name}} "> {{$p->name}} </a></h3>

                                                        <div class="description std">
                                                            <div class="inner">The must-have tee for his third birthday!</div>
                                                        </div>
                                                        <textarea name="description[6]" rows="3" cols="5" title="Comment" placeholder="Please, enter your comments..."></textarea>
                                                    </td>
                                                    <td>
                                                        <div class="cart-cell">

                                                            <div class="price-box" itemscope itemtype="http://ift.tt/GXPmjp"> <span class="regular-price" id="product-price-258"> <span class="price"  content="{{$p->salary}}">${{$p->salary}}</span> </span>
                                                            </div>

                                                            <div class="add-to-cart-alt">
                                                                <input type="text" class="input-text qty validate-not-negative-number" name="qty[6]" value="1" />
                                                                <button type="button" title="Add to Cart" onclick="addWItemToCart(6);" class="button btn-cart"><span><span>Add to Cart</span></span>
                                                                </button>
                                                            </div>
                                                            <p><a class="link-edit" href="#">Edit</a>
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                    <form method="DELETE" action="{{action('listController@deleteProduct','id='.$l->id)}}" enctype="multipart/form-code">
                                                    {!! csrf_field() !!}
                                                    <input type="hidden" name="id" value="{{$l->id}}">
                                                    <button type="submit" class="btn btn-danger">Remove item</button>
                                                    </form>
                                                    </td>
                                                </tr>
                                                @endif
                                                @endif
                                                @endforeach
                                                @endforeach
                                            </tbody>
                                        </table>
                                        <div class="buttons-set buttons-set2">
                                            <button type="submit" name="save_and_share" title="Share Wishlist" class="button btn-share"><span><span>Share Wishlist</span></span>
                                            </button>
                                            <button type="button" title="Add All to Cart" class="button btn-add"><span><span>Add All to Cart</span></span>
                                            </button>
                                            <button type="submit" name="do" title="Update Wishlist" class="button btn-update"><span><span>Update Wishlist</span></span>
                                            </button>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                            <div class="buttons-set">
                                <p class="back-link"><a href="home"><small>&laquo; </small>Back</a>
                                </p>
                            </div>
                        </div>
                    </div><!-- /.em-col-main -->
                    <div class="col-sm-6 col-sm-pull-18 em-col-left em-sidebar">
                        <div class="em-wrapper-area02"></div>
                        <div class="em-line-01 block block-account">
                            <div class="block-title em-block-title"> <strong><span>My Account</span></strong>
                            </div>
                            <div class="block-content">
                                <ul>
                                    <li><a href="#">Account Dashboard</a>
                                    </li>
                                    <li><a href="#it/">Account Information</a>
                                    </li>
                                    <li><a href="#">Address Book</a>
                                    </li>
                                    <li><a href="#">My Orders</a>
                                    </li>
                                    <li><a href="#">Billing Agreements</a>
                                    </li>
                                    <li><a href="#">Recurring Profiles</a>
                                    </li>
                                    <li><a href="#">My Product Reviews</a>
                                    </li>
                                    <li><a href="#">My Tags</a>
                                    </li>
                                    <li class="current"><strong>My Wishlist</strong>
                                    </li>
                                    <li><a href="#">My Applications</a>
                                    </li>
                                    <li><a href="#">Newsletter Subscriptions</a>
                                    </li>
                                    <li class="last"><a href="#">My Downloadable Products</a>
                                    </li>
                                </ul>
                            </div>
                        </div><!-- /.em-line-01 -->

                    </div><!-- /.em-sidebar -->
                </div>
            </div>
        </div>
    </div>
</div><!-- /.em-wrapper-main -->


@stop

there is a problem with my code it regenerate the view and pass the id right but it didn't delete the required row in database , can anyone help ?



via Chebli Mohamed

How to show image in index view page in laravel 5?

index.blade.php

I am using img src="{{ URL::asset($task->image) }}" to display image but its not working...please suggest me on how to achieve it..

@extends ('welcome')

@section ('content')
<h1 class="headng"> Form List </h1>
    <table class="table  table-hover ">
        <tr>
            <th><h4>Title</h4></th>
            <th><h4>Description</h4></th>
            <th><h4>Image</h4></th>
            <th><h4>Printable</h4></th>
            <th><h4>Actions</h4></th>
        </tr>
        @foreach($tasks as $task)
        <tr>
            <td>{{ $task->title }}</td>
            <td>{{ $task->description }}</td>
            <td><img src="{{ URL::asset($task->image) }}" /></td>
            <td>{{ $task->printable }}</td>
            <td>
                <a href = '{{ action('TasksController@edit',[$task->id]) }}'>Edit</a> |
                {!! Form::open([
       'method' => 'DELETE',
       'route' => ['tasks.destroy', $task->id]
   ]) !!}
                {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
                {!! Form::close() !!}
            </td>
        </tr>
        @endforeach
    </table>
@stop



via Chebli Mohamed

Laravel 5 External JavaScript Files_ JavaScript stack

the following JavaScript is working perfect in side the test.blad.php file but when i made external test.js file at the browser i get some thing like

http://localhost:8000/%7B%7Burl('/barcode')%7D%7D?j_barcode=112234

instead of

 http://localhost:8000/barcode?j_barcode=112234

the code in test.js file is :

$(document).ready(function(){ 
 $('#barcode').keyup(function(event){
  if(event.keyCode == 13){            
            var j_barcode = $('#barcode').val();      
   $.get("{{url('/barcode')}}", {j_barcode:j_barcode},   function(data) {   
         console.log(data) ;
        //success data                                             
         $.each(data,function(i, obj){       
            document.getElementById("item").value =obj.itemName;
            document.getElementById("itemId").value = obj.id;

            console.log(data) ;
        });
      });

      } 
  });

});

and the route.php

Route::get('/barcode'    , 'testController@getBarcode');

at last i decleared the test.js in test.blade.php as

<script  type="text/javascript" src="/hsm/js/test.js" ></script>



via Chebli Mohamed

Get popular items by related table

I'm trying to get the most 'bidded' products.

I have a table auctions, and a table bids. Every bid record has a auction_id.

Now I want to get all auctions, but ordered by the most bidded, in an eloquent way. I've never done something like that before and can't seem to find a good answer.

Any ideas?



via Chebli Mohamed

Laravel 5 relationships hasOne save()?

I have two tables Projects and Galleries. Project has one gallery. In galleries table I have a foreign key project_id.

Schema::table('galleries', function (Blueprint $table) {

            $table->integer("project_id")->unsigned()->nullable()->default(null);

            $table->foreign("project_id")
                    ->references("id")
                    ->on("projects")
                    ->onDelete("set null");

        });

In Project model I have a function that gets the gallery associated with the project:

public function gallery()
  {
    return $this->hasOne("App\Gallery");
  }

When creating new project, user selects from drop down the gallery then when saving a new project, how can I update galleries table to use newly created projects_id

$gallery_id = 2; // user selected gallery 2

$project = new Project();
$project->title = "new project";
$project->save(); 



via Chebli Mohamed

antonioribeiro/firewall package throwing errors after upgrading to laravel 5.2.5?

I am working on a laravel application and decided to use antonioribeiro/firewall to manage IP restrictions throughout my application. The package is awesome and worked like a charm. Until recently when I upgraded to the latests laravel version 5.2.5 when the package started throwing and error, the stack to which I am pasting below:

[2015-12-29 09:23:20] local.ERROR: exception 'BadMethodCallException' with message 'Method filter does not exist.' in /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:81
Stack trace:
#0 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(163): Illuminate\Routing\Router->__call('filter', Array)
#1 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(163): Illuminate\Routing\Router->filter('fw-block-bl', '\\PragmaRX\\Firew...')
#2 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(67): PragmaRX\Firewall\Vendor\Laravel\ServiceProvider->registerFilters()
#3 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(531): PragmaRX\Firewall\Vendor\Laravel\ServiceProvider->register()
#4 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php(74): Illuminate\Foundation\Application->register(Object(PragmaRX\Firewall\Vendor\Laravel\ServiceProvider))
#5 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(507): Illuminate\Foundation\ProviderRepository->load(Array)
#6 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php(17): Illuminate\Foundation\Application->registerConfiguredProviders()
#7 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(203): Illuminate\Foundation\Bootstrap\RegisterProviders->bootstrap(Object(Illuminate\Foundation\Application))
#8 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(208): Illuminate\Foundation\Application->bootstrapWith(Array)
#9 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(105): Illuminate\Foundation\Console\Kernel->bootstrap()
#10 /home/vagrant/Code/archive/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 {main}  

Now I am not an expert but I think this line:

$this->app['router']->filter('fw-block-bl', '\PragmaRX\Firewall\Filters\Blacklist');

is responsible for throwing the error. My best guess is that maybe filters are deprecated in 5.2.5 and there is no longer a filter method or maybe it was renamed to something else. In either case I don't know how to fix this. I am not using the filters that ship with the package as it is. I have written my own custom middleware to work with. How do I go around this problem?



via Chebli Mohamed

JWT token_not_provided exception when using request validation with route::controller

Hello i have the following routes:

Route::group(['prefix' => '/api/v1/', 'namespace' => 'App\Http\Auth\Controllers'], function() {
    /**
     * Authentication
     */
    Route::controller('auth', 'AuthController');
    Route::controller('password', 'PasswordController');
});

And in my AuthController.php file i have this:

<?php namespace App\Http\Auth\Controllers;

use App\Models\User;
use App\Http\Auth\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;

use App\Http\Auth\Requests\LoginRequest;
use App\Http\Auth\Requests\RegisterRequest;

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

use App\Commands\SendEmail, App\Commands\SendSMS;

use App\Models\CustomerDetails;

use Hash, Session, Auth, DB;

class AuthController extends Controller {

    /**
     * the model instance
     * @var User
     */
    protected $user;
    /**
     * The Guard implementation.
     *
     * @var Authenticator
     */
    protected $auth;

    /**
     * Create a new authentication controller instance.
     *
     * @param  Authenticator  $auth
     * @return void
     */
    public function __construct(Guard $auth, User $user)
    {
        $this->user = $user;
        $this->auth = $auth;

        // Apply the jwt.auth middleware to all methods in this controller
        // except for the authenticate method. We don't want to prevent
        // the user from retrieving their token if they don't already have it
        $this->middleware('jwt.auth', ['except' => ['postRegister', 'postLogin', 'getLogout']]);
    }

public function postLogin(LoginRequest $request)
{
  ...
}

public function getRegister()
{
  return [
    'method' => 'getRegister'
  ];
}

public function postRegister(RegisterRequest $request)
{
  return [
    'method' => 'postRegister'
  ];
}

Now my issue right now is when i try posting to my postRegister() method i get a {"error":"token_not_provided"} exception returned. However when i take out the RegisterRequest $request it returns 'method' => 'postRegister'. I have no idea what is going on here and what my request file has to do with jwt auth token, especially since there is no JWT middleware on that route itself but rather inside the controller.

This is my RegisterRequest.php file:

<?php namespace App\Http\Auth\Requests;

use App\Http\Auth\Requests\Request;

class RegisterRequest extends Request {

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'fullname' => 'required|min:6',
            'phone' => 'required|numeric|min:10',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|confirmed|min:6'
        ];
    }

}



via Chebli Mohamed