jeudi 31 décembre 2015

GroupBy Query Laravel 5.1

I'm having problem in fetching the data using groupBy, I don't where I'm wrong, I have done it many times before, but today I'm wrong some where and I don't know where. Following is the Table from which I want to select the Data:

Table Name: user_questions

id | user_id | message | read_status_user | read_status_support | answered

Now suppose if one user sends more than one messages, then user_id will be repeated, So to want all the message from one particular user I'm firing the query like following:

UserQuestion::groupBy('user_id')->get();

This should give me the result like

user_id = 1 > message1
user_id = 1 > message2
....
user_id = 1 > message...(if any)

user_id = 2 > message1
user_id = 2 > message2
..... 
So on...

But this is always giving me only one message from the particular user. I don't know why. Is there any mistake? I have tried another queries too, but all are giving me the same result.

Please help me with this. Everybody's help will be highly appreciated. Thanks to all of you in advance.



via Chebli Mohamed

Laravel 5.2 Eloquent column name conflict

I have the following method in my user class:

/**
 * Get all organisations for user (if owner)
 *
 * @param
 */
public function getOrganisationsOwned()
{
    // If the user is owner of any one or many organisations then return this list
    return Organisation::join('users', 'organisations.owner_id', '=', 'users.id')
        ->leftJoin('subscription_plans', 'organisations.subscription_plan_id', '=', 'subscription_plans.id')
        ->where('users.id', '=', $this->id)
        ->select('organisations.*', 'subscription_plans.*')
        ->get();
}

The method essentially queries and joins two tables. Each table has a column called title.

The output from the above generates the rows as desired with the right info, but returns only one title column, from the right table (subscription_plans) but not the column title from the left table (organisations).

I understood that

->select('organisations.*', 'subscription_plans.*')

would make the query return both columns. What am I missing? Happy new year!



via Chebli Mohamed

Force delete Session records for the current login User : Laravel 5.2

What is it about ?

I am using Sessions table that keep accumulating the Current user login sessions in Sessions table.

What's the issue ?

Instead of manually deleting the record after login, Is there any way to force Laravel 5.2 to delete all current User associated records based on user_id ?



via Chebli Mohamed

Token Mismatch issue in IFrame in Internet Explorer. Laravel 5.2

What's the problem ?

I am facing Token Mismatch issue when accessing the site in IFrame in Internet Explorer.


What I tried so far ?

I search for the resolution and found this link

Below is the code that I found in the above link

App::after(function ($request,$response){
    if($request->is('external/*')){
        // IE iframe cookie fix
        $response->header('P3P', 
                  'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
    }
});


What's the question ?

Where should I write the above code in Laravel 5.2 ?



via Chebli Mohamed

laravel5.1 validate number

How to validate numbers using laravel validator. In my case I need to validate if a number is between "1.00" and "50.00".

As seperator between the number pairs the "." and the "," should be allowed. The number should have only two decimal places. Is there a way to get this done using standart laravel validators combined?



via Chebli Mohamed

Testing two forms on one page the `press` directive always submits the second form.

I am using Laravel 5.1 and whenever I test a page with two forms the second form is always submitted. If I remove the second form, or swap the order of the forms, the test works (but other tests then break). The page behaves as expected in the browser. Any help is appreciated.

edit.blade.php

    @section('content')
    <!-- Update Form -->
            {!! Form::model($article,
                    [
                        'id'=>'editForm', 
                        'method' => 'PATCH', 
                        'action' => ['ArticlesController@update', $article->id] 
                    ]) !!}

    <!-- Title Field -->
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title', null, ['id' => 'title']) !!}

    <!-- Content Field -->
        {!! Form::label('content', 'Content:') !!}
        {!! Form::textarea('content', null, ['id' => 'content']) !!}

    <!-- Save Button -->
        {!! Form::submit('Save', ['id' => 'save']) !!}

        {!! Form::close() !!}

    <!-- Delete Form -->
        {!! Form::model($article,
                [
                    'id'=>'deleteForm', 
                    'method' => 'DELETE', 
                    'action' => ['ArticlesController@destroy', $article->id] 
                ]) !!}

    <!-- Delete Button -->
        {!! Form::submit('Delete', ['id' => 'delete']) !!}

        {!! Form::close() !!}
    @stop

ArticlesTest.php

 /**
  * @group articles
  * @test
  */
public function it_edits_an_article()
{
    //$this->markTestSkipped('Test doesn\'t work with two forms on one page.');

    $article1 = factory(Figurosity\Articles\Article::class)->make();
    $article2 = factory(Figurosity\Articles\Article::class)->make();

    $user = factory(User::class)->create();

    $user->articles()->save($article1);
    $this->seeInDatabase('articles', 
        [
            'title' => $article1->title,
            'user_id' => $user->id
        ]);

    $this->actingAs($user)
        ->visit($this->articlesUrl)
        ->see($article1->title)
        ->visit('/articles/'.$article1->slug.'/edit')
        ->type($article2->title, '#title')
        ->type($article2->content, '#content')
        ->press('Save') //this presses the delete button
        ->seePageIs($this->articlesUrl)
        ->see($article2->title)
        ->visit('/whats-new/'.$article1->slug)
        ->see($article2->content)
        ->visit('/latest/'.$article2->slug)
        ->see($article2->content)
        ->seeInDatabase('articles', ['title' => $article2->title]);
}



via Chebli Mohamed

laravel 5.1 make rss feed

i make application with Laravel 5.1 only i need get some posts as Xml i mean rss feed i am USING LARAVEl 5.1 i found a lot of solutions But for Laravel 4 doesn't work for me

i tired this code but how can i path my data to view

return response('rss', 200,['Content-Type'=> "application/xml"]);

and this

return response($posts, 200,['Content-Type'=> "application/xml"]);

but this code return only json data

i need help thanks every one i am USING LARAVEl 5.1 :) and happy new year



via Chebli Mohamed

laravel 5 authenticate problems

My authenticate system does not work (with laravel 5.1). Can you please help me ? I am a beginner in Laravel , certainly I forgot something, but I do not know what.

I have this response :

FatalErrorException in personne.php line 10: Class 'App\Models\Eloquent' not found

My auth.php :

 'driver' => 'eloquent',

/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/

// 'model' => App\User::class,
    'model' => 'App\Models\personne',

My personne class :

 namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class personne extends Eloquent implements UserInterface, RemindableInterface {


    protected $table = 'personne';
    protected $primaryKey = 'id_personne';
    public $timestamps = false; // pour ne pas que laravel update lui même les champs dates de la table


    public function getReminderEmail()
    {
        return $this->email;
    }

etc....

My controller :

    namespace App\Http\Controllers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Auth;

class AuthentificationController extends Controller {

Thanks a lot.

Dominique



via Chebli Mohamed

Eloquent where clause with multiple condtion filter

In my database table i have A TABLE named student add i want to fetch the specific student who has all the following condition stored in filters array with some other option ("like name can be middlename or lastname")

$filters = [
                ['type' => 'name', 'value' => 'Abhishek'],
                ['type' => 'roll', 'value' => '0013']
            ];

i am trying to fetch that data with following code

 $student = Student::where(function ($query) use ($filters) {

            foreach($filters as $filter) {
                switch($filter['type']){
                    case 'name' :
                        $query->where('firstname', $filter['value'])
                        ->orWhere('middlename', $filter['value'])
                        ->orWhere('lastname', $filter['value']);
                        break;
                    case 'roll' :
                        $query->where('rollnumber', $filter['value']);
                        break;

                }
            }
        })
        ->get();

i am using advance where clause here but it is running for first parameter(like name) only means i am getting value where name = filters['value'] why it is so



via Chebli Mohamed

Laravel 5.2 chaining methods

Happy new year! I am new to Laravel 5 and I am playing with it for the last time in 2015, and I am stuck.

I have two tables:

organisations contains:

id   name   address   subscription_plan_id   .... other columns
--   ----   -------   --------------------
1    xyz    123 St    23

subscription_plans contains:

id   name      cost    .... other columns
--   -------   -----
23   monthly   12.00

I have a class for each where I set up the following Eloquent relationships:

Class Organisation:

public function subscriptionPlan()
{
    return $this->hasOne(SubscriptionPlan::class, 'id', 'subscription_plan_id');
}

Class SubscriptionPlan:

public function subscriptionPlan()
{
    return $this->belongsTo(SubscriptionPlan::class, 'subscription_plan_id', 'id');
}

In my controller I want to create a collection with selected columns from each table, using the Eloquent relationships, but I have not managed to do this without essentially using SQL... I extract each collection with the following commands:

$subscriptionPlans = SubscriptionPlan::all();

$organisations = Organisation::all();

How do I extract one collection chaining the relationships and nominating the columns I want?

Something like the blow (which does not work):

$organisationsAndPlans = Organisation::all()
         ->subscriptionPlan()
         ->get('organisations.col1', 'subscription_plans.col3');



via Chebli Mohamed

mercredi 30 décembre 2015

Laravel - How to check reset password email sent successfully to the user?

I have following function postEmail in my PasswordController.php and calling when user trying to reset password.

/**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postEmail(Request $request)
    {
        //echo Input::get('ID'); die;
        $this->validate($request, ['ID' => 'required|email']);

        // Pass data to reset password mail template
        view()->composer('emails.password', function($view) {
            $view->with([
                'UserProduct1'   => 'UserProduct1',
                'UserProduct2'   => 'UserProduct2',
            ]);
        });

        $response = Password::sendResetLink($request->only('ID'), function (Message $message) {
            $message->subject($this->getEmailSubject());
        });

        switch ($response) {
            case Password::RESET_LINK_SENT:
                return redirect()->back()->with('status', trans($response));

            case Password::INVALID_USER:
                return redirect()->back()->withErrors(['ID' => trans($response)]);
        }
    }

Is there any way to check, reset email sent or not to the user in laravel.

Any Idea?

Thanks.



via Chebli Mohamed

Scaffold Controller Laravel 5.2 Artisan

I am running following command:

php artisan make:controller UserController

This is successfully creating Controller but i want to scaffold it with all the basic methods. Can someone tell how i can do that. Thanks



via Chebli Mohamed

Laravel CSRF value empty

I am trying to add csrf in my laravel web app as meta tag -

<meta name="csrf-token" content="{{ csrf_token() }}">

but the value is empty when I browse it -

<meta name="csrf-token" content="">

I have also tried adding in login form also - as {!! csrf_filed() !!} or

<input type="hidden" name="_token" value="{{ csrf_token() }}">

but in both case value is null. I am using Angularjs in front end, does it have to do anything with that?



via Chebli Mohamed

Ajax combo box in laravel 5

I have a problem in implementing AJAX in Laravel 5 with blade syntax. I have 2 simple dropdowns. For example dropdown A and dropdown B. If dropdown A value is 1, I want the dropdown list in B to be Apple and Avocado. If dropdown A value changed to 2, the dropdown list in B will be Banana and Blueberry. I have no problem when doing it with just PHP and AJAX. Here is my code :

in main.php

<script type='text/javascript'>
        $(function(){
            $('#alphabet').change(function(){
                console.log($(this));
                $.get( 'fruit.php' , { option : $(this).val() } , function ( data ) {
                    $ ( '#fruit' ) . html ( data ) ;
                } ) ;
            });
        });
    </script>

    <div class='form-group'>
        <label class='control-label col-sm-4'>Alphabet</label>
        <div class='col-sm-6'>
            <div class='dropdown'>
                <select style='width: 261px' class='form-control' name='alphabet' id='alphabet'>
                    <option value='0' selected='' >-Choose-</option>
                    <option value='1'> 1 </option>
                    <option value='2'> 2 </option>
                </select>
            </div>
        </div>
    </div>

    <div class='form-group'>
        <label class='control-label col-sm-4'>Fruit</label>
        <div class='col-sm-6'>
            <div class='dropdown'>
                <select style='width: 261px' class='form-control' name='fruit' id='fruit'>
                    <option value='0' selected='' >-Choose-</option>
                </select>
            </div>
        </div>
    </div>

in fruit.php

<?php
$Options = Array ( 
    1 => Array ( 
        'Apple' ,
        'Avocado'
    ) , 
    2 => Array ( 
        'Banana' ,
        'Blueberry'
    )

) ; 

forEach ( $Options [ $_GET [ 'option' ] ] as $Item ) {
    printf ( '<option value="%s">%s</option>' , $Item , $Item ) ;
}

How can I implement this on Laravel 5?



via Chebli Mohamed

Send email from queued event

I use Lumen 5.1 and have a pretty standard event handler that should send an email:

<?php

namespace App\Handlers\Events;

use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\UserHasRegistered;
use Illuminate\Contracts\Mail\Mailer;

class SendWelcomeEmail implements ShouldQueue
{
    protected $mailer;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function handle(UserHasRegistered $event)
    {
        $user = $event->user;

        $this->mailer->raw('Test Mail', function ($m) use ($user) {
            $name = $user->getFirstName().''.$user->getLastName();

            $m->to($user->auth()->getEmail(), $name)->subject('This is a test.');
        });
    }
}

The email is sent when I don't use the ShouldQueue interface. But when I push the event handler to the queue (i. e. use the ShouldQueue interface), the email is not sent and I don't get any error messages.

Do you have any ideas how to solve or debug this?



via Chebli Mohamed

Clear User Session if opened account from multiple Browsers. Laravel 5.2

What is it about ?

The database session driver now includes user_id and ip_address so you can easily clear all sessions for a given user.

What's the Problem

I checked this Article while reading what's new in Laravel 5.2

Firstly, I am using In-built authentication system that Laravel provides. I am assuming that if I login into my account in Firefox and at the same time, same credentials are being used to access the account in Internet Explorer, then as per the above article, I will be logged out.

But this is not happening. Am I missing something ?



via Chebli Mohamed

Blade not displaying model values from the database

I am trying to display the list of products for a user, and to my surprise this does not display it on the page, though, it is inserted into the database, what could be wrong?

public function index()
        {
            $listProducts = Product::where('user_id', '=', Auth::user()->id)->orderBy('productname', 'desc');
            return view('product.index')
            ->with('products', $listProducts);
        }

Blade file:

@if(Auth::check())
                        @foreach($products as $product)

                                <TR><TD>{!! $product->companyname !!}</TD><TD>{!! $product->productname !!}</TR>

                        @endforeach
                    @endif



via Chebli Mohamed

Laravel - Connection could not be established with host smtp.gmail.com

I'm trying to send an email using the standard email feature in Laravel 5.

I'm using smtp from google to send mails. When working local the email sends without a problem. But when I'm trying to do the same on my hosting (one.com) I get the following error.

Swift_TransportException in StreamBuffer.php line 265:
Connection could not be established with host smtp.gmail.com [Connection timed out #110]
in StreamBuffer.php line 265
at Swift_Transport_StreamBuffer->_establishSocketConnection() in StreamBuffer.php line 62
at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'tcp', 'host' => 'smtp.gmail.com', 'port' => '587', 'timeout' => '30', 'blocking' => '1', 'tls'     => true, 'type' => '1')) in AbstractSmtpTransport.php line 113
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79



via Chebli Mohamed

How can I set a session var using javascript and get it via php code

I have a javascript code like this :

<script type="text/javascript">

    $('#editRole').on('show.bs.modal', function (e) {  

        $roleID =  $(e.relatedTarget).attr('data-id');
        // Here I want to set this $roleID in session may be like this :
        Session['roleID'] = $roleID;                      
    });    

</script>

Then I want to get that $roleID in an other place using php code, may be like this :

<?php $roleID = Session::get('roleID'); //do something ....  ?>

Thanks



via Chebli Mohamed

Custom attribute (read-only) in Laravel 5.1

I have Cam model and for each cam I have a folder with images on server. I just need to get all image names in custom attribute but I don't get it. There is no need to call actions within table. I tried extending constructor but no luck.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cam extends Model
{
    protected $table = 'cams';
    protected $guarded = 'id';
    public $timestamps = false;
    public $images = null;

    public function __construct($attributes = array())
    {
        parent::__construct($attributes);

        $this->images = 'kk';
    }

    public function getVideosAttribute($value) {
        return explode(',', $value);
    }

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



via Chebli Mohamed

Mail Queue and DOMPDF job works perfectly on homestead, but not on my production server

Latest 5.1 Laravel 5.1.27 Latest dompdf 0.6.2

So i have an email, that attaches a generated PDF, that is queued.

Tested on homestead, both manually with artisan:work and artisen:listen, it all works well, i receive the email perfectly with the attached PDF.

Only in my production server, that has same parameters, at least for what i can see, doesnt work!!

It all works if synchronously with Mail::send

When updated to Mail:queue, i get the Job stuck, on production i have supervisor with artisan:listen --tries=10 and it gets failed, and moved to the failed_jobs table.

Aah, mail::queue workes perfectly if without PDF attachment

So i could nail it down to the exception thrown by DOMPDF, only in production and only in a queued job!

exception 'ErrorException' with message 'Undefined index: SCRIPT_FILENAME' in /home/myapp_name/vendor/dompdf/dompdf/include/stylesheet.cls.php:147

So this line on stylesheet.cls.php:147 is

list($this->_protocol, $this->_base_host, $this->_base_path) = explode_url($_SERVER["SCRIPT_FILENAME"]);

So all comes down to being on CLI (command line interface), that doesn't have this $_SERVER["SCRIPT_FILENAME"] defined!!

All would make sense to go down this road, but why the heck does it work perfectly when job processed in homestead, also on CLI??

Hope i make sense!! Code for the queue

$data = [bla bla bla]; // this $data is for the blade render, and is different from the one used in the Closure, for the PDF, i know =)
    Mail::queue('emails.default', $data , function($message) use ($destinatarios, $user_spo_full_name, $spare_part_order, $spare_parts_order_list)
    {
        $message->to($destinatarios);
        $message->subject('Spare Part Order Confirmation - Your ref: ' . $spare_part_order->client_reference );

        $data =
            [
                'user_full_name' => $user_spo_full_name,
                'spare_part_order' => $spare_part_order,
                'spare_parts_order_list' => $spare_parts_order_list
            ];
        $pdf = PDF::loadView('spareparts.sparepartsorder.pdf.spare-part-order', compact('data'));
        $message->attachData($pdf->output(), 'SP_'.$spare_part_order->client_reference . '.pdf' );

    });

Thanks in advance for any help and happy new year all!!



via Chebli Mohamed

Laravel returns htmlentities() expects parameter 1 to be string, object given

I have the following Laravel 5.1 controller function

public function editare($prod_id) {

    $categorii=DB::table('categorii_produse')
        ->select('cat_id')
        ->get();

    $categorie_selectata=DB::table('produse')
        ->leftjoin('categorii_produse','prod_cat_id','=','cat_id')
        ->where('prod_id','=',$prod_id)
        ->select('prod_cat_id')
        ->get();

    $articole=DB::table('produse')
        ->leftjoin('imagini','prod_id','=','img_prod_id')
        ->where('prod_id','=',$prod_id)
        ->get();


    return view ('pagini.editare',compact('categorii','categorie_selectata','articole'));

And the following line in the view which has problems

{!! Form::select('categorii',$categorii, null, ['class' => 'form-control']) !!}

The view returns the following error

htmlentities() expects parameter 1 to be string, object given



via Chebli Mohamed

n-n relationship with an additional value for the same table in laravel

I'm quite new to Laravel, and I'm trying to figure the correct way to design my database schema before starting anything.

So, here is the deal :

  • I'm creating an application on which users should have to create an account. I'll need a users model/db table. No problem here.
  • These users will be able to mention some of their friends. These friends should then be able to register and become legitimate users, or they won't.
  • I wanted first to make two tables, but as the friends can become users as well, I thought adding them to the users table was quite logical (With something like a unregistered flag while they are not registered).

The catch is, I think Laravel is able to make automatically a correct n-n relationship between users and users, but I also wanted to allow the first users to add a pseudonym for their friends. In a "regular" database, I'd add the pseudonym field in the relationship database, but is it possible with Laravel, and how ?

After reading myself, I'm maybe not very self-explanatory. Si, here are the possible user stories :

  • I create my account
  • I mention my friend bob with his email, it creates a new user with only the email, and a relationship between me and bob in where I call him "friend"
  • Alice creates her account, and mentions bob. It links her user account with bob's, but in the relashionship table she calls him "sweetie"
  • Bob creates his account. Its users database entry is completed with his personal information / pseudonym, but Alice and I still see him as friend/sweetie

Sorry for being this talkative.



via Chebli Mohamed

Laravel 5.1 - Pass parameter to Breadcrumbs

I use davejamesmiller Breadcrumbs package. I am wondering how to pass a parameter to a breadcrumb, something like an id.

In the docs (here) it says that is possible, but can't find the way to do it.

My goal es to do a breadcrumb like this: Dashboard \ User \ New Model. Where New Model its a form to add model data with some relationship with the user. Without the user_id param the link for User won't work.

Any idea?



via Chebli Mohamed

How delete image in frozennode administrator?

I use laravel 5.1 framework and froznnode administrator latest version 5.0.11. When I upload a image via frozennode and then delete it or cancel it doesn't delete actually. Any suggestion how to solve this problem?



via Chebli Mohamed

laravel5.1 edit sendResetLink() function

How did I need to edit this code:

$response = Password::sendResetLink($request->only('username'),     function (Message $message) {
        $message->subject($this->getEmailSubject());
        $message->from('hello@app.com', 'Your ApplicationZ');
    });

So I can use this e-mail template:

Hey {{ $username }}
Click here to reset your password: {{ url('reset/'.$token) }}

The difference to the default function is to use the username to say a nice hello to the user. I don't want to rewrite the whole password "reset" method.



via Chebli Mohamed

Laravel - How to pass variable to reset password template?

I have implemented reset password functionality with Laravel 5 and getting email. Now how to pass some variable data to my email template to display more information about user.

/**
 * Send a reset link to the given user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function postEmail(Request $request)
{
    //echo Input::get('ID'); die;
    $this->validate($request, ['ID' => 'required|email']);

    $UserProduct = "Sample 1"; // I want to pass this variable to my password.blade.php
    $response = Password::sendResetLink($request->only('ID'), function (Message $message) {
        $message->subject($this->getEmailSubject());
    });

    switch ($response) {
        case Password::RESET_LINK_SENT:
            return redirect()->back()->with('status', trans($response));

        case Password::INVALID_USER:
            return redirect()->back()->withErrors(['ID' => trans($response)]);
    }

}

I want to print $UserProduct = "Sample 1"; to my email template but don't know how to pass to the password.blade page.

Any idea?

Thanks.



via Chebli Mohamed

get related model without loop query

tables:

products:

id | name | author_id    

authors:

id | name

models:

product:

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

Then I get products:

$products = Product::where('name','like','username%')->get();
foreach ($products as $product) {
    $product->author;
}

Is there any way to get products with author without loop?



via Chebli Mohamed

Strange behaviour with image input in laravel 5.1

I have an issue with my current web project.

For what I am currently trying to do, I need to check if my request contains an input called image.

So i just apply the normal method :

if($request->has('image'))
{
    ...
}

But for some reasons, this is not working : laravel

Can someone explain me why ?



via Chebli Mohamed

Why does a Laravel resource controller limited to update generate two routes?

Given the following defined route in routes.php:

Route::resource('smoker','SmokerController',['only' => ['update']]);

..results in the generation of two distinct routes:

| PUT   | profile/smoker/{smoker}| profile.smoker.update | App\Http\Controllers\Profile\SmokerController@update |
| PATCH | profile/smoker/{smoker}|                       | App\Http\Controllers\Profile\SmokerController@update |

I can hazard a guess that both PUT and PATCH verbs are close enough in a restful environment that they both fall under an 'update' restriction. I can't find any documentation to support that guess, nor can I find anywhere documentation why one (PUT) has it's alias automatically set, in this case, to profile.smoker.update.

What is more confusing, is that a similar restriction, 'show', results in a verbs GET and HEAD being merged as GET|HEAD in the route list.

| GET|HEAD | profile/smoker/{smoker}| profile.smoker.show | App\Http\Controllers\Profile\SmokerController@show |

Why is GET and HEAD merged, but PUT and PATCH not?



via Chebli Mohamed

Laravel 5 middleware auth always fails and redirects to login

I am authenticating my user and redirecting him to dashboard if credentials are correct. I want to secure the dashboard route and added middleware auth, but now it always redirects to login page.

Routes.php

Route::get('login', array('uses' => 'HomeController@showLogin'));
Route::post('login', array('uses' => 'HomeController@doLogin'));
Route::get('logout', array('uses' => 'HomeController@doLogout'));

Route::group(['middleware' => 'auth'], function() {
    Route::get('/', function () {
        return view('dashboard');
    });
    Route::get('dashboard', function () {
        return view('dashboard');
    });
});

HomeController.php

public function showLogin(){
    return View::make('login');
}

public function doLogin(Request $request){
    $rules = array(
        'email'    => 'required|email',
        'password' => 'required|alphaNum|min:3'
    );
    $validator = Validator::make($request::all(), $rules);
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator)
            ->withRequest($request::except('password'));
    }
    else {
        $userdata = array(
            'email'     => $request::get('email'),
            'password'  => $request::get('password')
            /*'password' => Hash::make($request::get('password'))*/
        );
        if (Auth::attempt($userdata)) {
            $userid = Auth::id();
            return redirect()->intended('/');
        } else {
            return Redirect::to('login');
        }
    }
}

public function doLogout()
{
    Auth::logout();
    return Redirect::to('login');
}

Middleware Authenticate.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    return $next($request);
}

Middleware RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
}



via Chebli Mohamed

Laravel Storage returns: mkdir(): File exists

When I'll try to check if a file exists in Laravel 5.1 I am always getting this error:

ErrorException in Local.php line 95: 
mkdir(): File exists

I don't know what could here be wrong, I want to check if a file exists or not with:

$exists = Storage::disk('images')->has('filename.jpg');

dd($exists);

Disk "images":

'disks' => [

    'local' => [
        'driver' => 'local',
        'root'   => storage_path().'/app',
    ],

    'images' => [
        'driver' => 'local',
        'root'   => storage_path().'/app/images',
    ],

Any ideas?



via Chebli Mohamed

Onchange function not working using laravel5

Onchange function not working using laravel5.here i select the second category from same table.i can get the first category id.onchange function is the problem.what i need to change. Controller

public function ajax_select_sub_second_cat()
{

     $id =  $_GET['id'];
     $main_cat = Category_model::get_sub_category_ajax($id);
    //return view('siteadmin.add_cat',['main_cat' => $category]);
    if($main_cat)
    {
        $return  = "";
        $return  = "<option value='0'> -- Select -- </option>";
        foreach($main_cat as $main_cat_ajax) {

        $return .= "<option value='".$main_cat_ajax->sub_category1."'> ".$main_cat_ajax->sub_category1." </option>";        
        }
        echo $return;
    }
    else
    {
    echo    $return = "<option value='0'> --Select-- </option>";
    }
}

view

<select id="subcategory" name="product_sub_category" onChange="getCat1(this.value);"> 

-----Select Standard-----

  <script>
  function getCat1(id)
     {
   var passData = 'id='+id;
   $.ajax( {
        type: 'get',
      data: passData,
      url: '<?php echo url('ajax_select_sub_second_cat'); ?>',
      success: function(responseText){  
       if(responseText)
       { 
      $('#subcategory2').html(responseText);            
       }
    }   
  }); 

}

  </script>



via Chebli Mohamed

laravel blade template not rendering

Getting into laravel and im trying to work with blade templating but its not rendering. All my examples are coming for the laravel documentation.

UPDATE
So here is my master.blade.php file located in resources > views > master.blade.php

<!DOCTYPE html>
<html>
    <head>

        @yield('layouts.header')
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">Test to Laravel 5</div>
            </div>
        </div>
    </body>
</html>

and here is my header.blade.php file located in view/layouts/

@section('header')
    <title>cookie monster</title>
    <link href="http://ift.tt/1R6X9hF" rel="stylesheet" type="text/css">
    <style>
        html, body {
            height: 100%;
        }

        body {
            margin: 0;
            padding: 0;
            width: 100%;
            display: table;
            font-weight: 100;
            font-family: 'Lato';
        }

        .container {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }

        .content {
            text-align: center;
            display: inline-block;
        }

        .title {
            font-size: 96px;
        }
</style>
@endsection

when i try to render my page no styles are being added even tho i have inline css at the moment, because i'm just testing how blade template engine works.



via Chebli Mohamed

mardi 29 décembre 2015

Using a CustomRequest for Form Validation in Laravel 5.1 fails?

I've created a custom Request called CustomerRequest that I want to use to validate the form fields when a new customer is created. I cannot get it to work, it appears to be continuing into the store() method even when it should fail.

I have three required fields: givenname, surname, email

Here is my CustomerRequest:

public function rules()
{
    return [
        'givenname' => 'required|max:3',
        'surname' => 'required',
        'email' => 'required|unique:customers,email',
    ];
}

Here is my CustomerController:

use pams\Http\Requests\CustomerRequest;

-----------------------------------------

public function store(CustomerRequest $request, Customer $customer)
{
    $request['created_by'] = Auth::user()->id;
    $request['modified_by'] = Auth::user()->id;

    $customer->create($request->all());

    return redirect('customers');
}

When I submit the form using a givenname of "Vince" it should fail because it is greater than 3 characters long, but instead I get this error:

FatalErrorException in CustomerController.php line 52: Cannot use object of type pams\Http\Requests\CustomerRequest as array

Line 52 in the controller is $request['created_by'] = Auth::user()->id;

From what I understand, if the CustomerRequest fails then the user should be redirected back to the customers.create page and not run the code contained in the store() method.



via Chebli Mohamed

Form model data not running correctly on @yield Laravel 5

all I want is to define the form model on template and then put a yield as the content of form data. But it cannot assign the model data correctly into each field that has been defined. This is my code:

template.detail.blade.php

@extends('admin.template.lte.layout.basic')

@section('content-page')
    {!! Form::model($model, ['url' => $formAction]) !!}
        @yield('data-form')
    {!! Form::close() !!}
    @if ($errors->any())
@stop

partial.edit.blade.php

@extends('template.detail')
@section('data-form')
    <div class="form-group">
        {!! Form::label('Dal_Name', 'Alternative Name', ['class' => 'required']) !!}
        {!! Form::text('Dal_Name', null, ['required', 'class' => 'form-control', 'placeholder' => 'Enter Alternative Name']) !!}
    </div>

    <div class="form-group">
        {!! Form::label('Dal_DssID', 'DSS Period', ['class' => 'required']) !!}
        {!! Form::select('Dal_DssID', $dssOptions, null, ['class' => 'form-control']) !!}
    </div>

    <div class="checkbox">
        <label for="Dal_Active">
            {!! Form::hidden('Dal_Active', 'N') !!}
            {!! Form::checkbox('Dal_Active', 'Y') !!}
            Active
        </label>
    </div>
@stop 

My Controller part:

     /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->data['model'] = DssAlternative::find($id);
        $this->data['formAction'] = \Request::current();
        $this->data['dssOptions'] = Dss::lists('Dss_Name', 'Dss_ID');
        return view('partial.edit', $this->data);
    }

But the model data does not propagate to form correctly. Sorry for my bad english.



via Chebli Mohamed

FIND_IN_SET with two strings

I have this EMPLOYEE table of employees list

+-----+---------------+-------------+
| ID  |EMPLOYEE_ID    | SKILLS      |
+-----+---------------+-------------+
|  1  |       1       |   3,4       |
+-----+---------------+-------------+
|  2  |       2       |   3,5,2     |
+-----+---------------+-------------+
|  3  |       3       |  1,5        |
+-----+---------------+-------------+

and table POSTED_JOB listing jobs

+-----+---------------+-------------+
| ID  |POSTED_JOB_ID  |  JOB_SKILLS |
+-----+---------------+-------------+
|  1  |       1       |   1,2,3     |
+-----+---------------+-------------+
|  2  |       2       |   3,4       |
+-----+---------------+-------------+
|  3  |       3       |   5,4       |
+-----+---------------+-------------+
|  4  |       4       |   5,6       |
+-----+---------------+-------------+

How can I get all jobs posted with skills corresponding to the skills of employees with laravel query.

For example for employee with employee_id 1, the jobs would be 1,2, and 3.

I tried with find_in_set but here both are lists. DB::raw("find_in_set(EMPLOYEE.SKILLS , POSTED_JOB.JOB_SKILLS)"), DB::raw(''), DB::raw(''))



via Chebli Mohamed

Can not update database when missing field in json

I am making an api that can help user update their info follow the input data. But when in input json have field "password" it will update successfully but when json don't have this field i can not update data in database. This is code i used to update data:

public function updateUserInfo(Request $request){
        $postData = $request->all();
        $data = json_decode($postData['postData'], true);
        if(isset($data['password'])){
            $data['password'] = bcrypt($data['password']);
        }
        $popData = $data['UserId'];
        unset($data['UserId']);
        $updateInfo = array();
        foreach($data as $info){
            if($info != null){
                $updateInfo[] = $info;
            }
        }
        $result =  DB::update(GeneralFunctions::makeUpdateString($data, 'User', ' UserId = '.$popData), $updateInfo);
        if($result != null && $result == true){
            return response()->json(['success'=>true, 'data'=>'Update Successful']);
        }else{
            return response()->json(['success'=>false, 'error'=>'We have encountered an error, try again later!']);
        }
    }

This is the json when everything work fine:

$postData = '{ "UserId" : "1",   "password":"12345", "UserName": "minhkhang",  "Address": "11/200" }'

This is the json which will cause error because it is missing password field:

$postData = '{ "UserId" : "1", "UserName": "minhkhang",  "Address": "11/200" }'

This is code i used to make update string follow input json:

 public static function makeUpdateString($keyvalarr, $table, $where){
        $stringSQL = 'UPDATE '.$table. ' SET ' ;
        foreach($keyvalarr as $fieldname => $updateval){
            if($updateval != null){
                $stringSQL .= $fieldname.' = ? , ';
            }
        }
        $stringSQL =  substr($stringSQL, 0, -2);
        if($where != null){
            $stringSQL .= 'WHERE '.$where;
        }
        return $stringSQL;
    }

Thank you.



via Chebli Mohamed

Should I use Laravel's Authorization or Zizaco's Entrust?

Laravel 5.1.11 already has been updated with Authorization. Zizaco's Entrust has been around for a while now. Which should we use to authorising users?



via Chebli Mohamed

Php artisan not working (laravel 5.1)

Suddenly when i type php artisan or any artisan command i seen this message

[ErrorException]
Trying to get property of non-object

I tried the following

1- php artisan clear-compiled

2- To delete vendor directory and use composer install Or composer update

3- clone a standard Laravel app and put my files app dir and my config and use composer commands but with step the error has changed to be

[ErrorException]
Trying to get property of non-object

Script php artisan clear-compiled handling the post-install-cmd event returned with an error

[RuntimeException]
Error Output:

Any Suggestions ?

Thanks



via Chebli Mohamed

include external php files(not in laravel directory) in laravel

I want to include an external PHP file into my service provider, that file is in a different folder. Like my file is in folder1 and this folder is at same level as laravel is.

   C:\xampp\htdocs\registration\php\file.php //this is file
   C:\xampp\htdocs\_problem_sharing\app\AppServiceProvider

This is how I am trying right now

include_once "/../../../registration/php/user_info.php";



via Chebli Mohamed

Call to a member function isClient() on a non-object

I am getting below error

Call to a member function isClient() on a non-object

When is it occurring ?

I have a Post route http://localhost/auth/logout When I press the logout button then this action method gets called.

Below is my User model

class User_Model extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'tblusers';

    protected $fillable = ['UserName', 'EmailAddress', 'Password', 'RoleID', 'IsActive'];

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

    protected $primaryKey = "UserID";

    public function isClient() 
    {
        return $this->RoleID == \App\Enumeration\Role\RoleType::Client ? 1 : 0;
    }
}

Below is my route.php file

<?php
Route::group(['middleware' => 'web'], function() {

    Route::get('/View-Profile', 'User\Account_Controller@ViewProfile');
    Route::get('/auth/logout', 'Auth\AuthController@getLogout');
});

Question

Am I missing something ?



via Chebli Mohamed

Laravel posts and tags: has many through relationship?

I'm making a Laravel application.

I have a posts table that stores "blog posts". I also have a tags table to store tags (eg: "Cooking" for cooking posts, "Books" for book posts). Each post can have many tags. I setup my database as such

Posts

  • id
  • text
  • title

Tags

  • id
  • name

PostTags

  • id
  • tag_id
  • post_id

Is this a "HasManyThrough" relationship in Laravel/Eloquent? I tried setting up my model using

public function tags()
{
   return $this->hasManyThrough('App\Tag', 'App\PostTag')
}

However, this isn't working - throwing exceptions telling me the column names don't exist.



via Chebli Mohamed

saving JSON string in laravel

I am trying to save a JSON string to the database.

this is the error that I get:

exception 'ErrorException' with message 'preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

And this is how my JSON looks like:

"metadata": {
      "is_ivr": 0,
      "is_upgradable": 1,
      "is_sms": 0,
      "is_design": 0,
      "threshold_amount": 0,
      "post_threshold": 0,
      "pre_threshold": 0
    }

I want to save the value of metadata as string.

I tried doing this:

$data = $request->input('data');
$data['metadata'] = json_encode($data['metadata']);

Result of dd($data);

array:8 [
  "product_name" => "Pulse"
  "parent_product" => 0
  "product_description" => "goes here"
  "metadata" => array:7 [
    "is_ivr" => 0
    "is_upgradable" => 1
    "is_sms" => 0
    "is_design" => 0
    "threshold_amount" => 0
    "post_threshold" => 0
    "pre_threshold" => 0
  ]
  "price_period" => 1
  "price_variation" => 2
  "outlet_pricing" => 0
  "status" => 1
  ]
]



via Chebli Mohamed

CakePHP Session User ID Sharing via memcached

I have CakePHP 5.2 using memcached

How can i share the user_id information from the CakePHP session to another Framework, Laravel 5.1 ?



via Chebli Mohamed

Is there any method/way to find out all the functions of some class in laravel?

I am understanding Laravel(5.1 version although 5.2 now recently comes) framework...and studying it deeply...What I am trying to ask let me elaborate through some example:
I have created the model named Blog:

namespace App; 
use Illuminate\Database\Eloquent\Model;
class Blog extends Model {
protected $fillable = ['title','body'];
}

Now in my controller I am accessing the function create() of this class in my controller store() method like:
public function store(BlogRequest $request) { $input = Request::all(); Blog::create($input); return redirect('blogs'); }
As you can see that in above controller method we are accessing the static function/method create() i.e
Blog::create($input)
..so the question is as there are so many other methods exists like create() method of a model(Blog) class which extends the Model class...is there any way/strategy/function to find out/know all the functions of this Model Class...



via Chebli Mohamed

Laravel 5.1 FatalErrorException in RegistersUsers.php line 32

since a few time I started programming in Laravel for a schoolproject. Now I tried to implement a login system. My database for userinformation is running on my homestead virtual machine, running with Postgresql. I already migrated the tables, so they exist and the database is running. Problem is: When I fill in the registrationform and send it, I get an error:

FatalErrorException in RegistersUsers.php line 32: Call to a member function fails() on null

You can see the code of RegistersUsers.php underneath:

    <?php
namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait RegistersUsers
{
    use RedirectsUsers;

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getRegister()
    {
        return view('auth.register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        Auth::login($this->create($request->all()));

        return redirect($this->redirectPath());
    }
}

When I try to log in it gives the warning the log in credentials doesn't exist in the database (because I haven't registered yet), so it seems that the database connection works properly.

Does someone know a solution for this?



via Chebli Mohamed

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

Logged in but Auth::user() always returns null - Laravel 5.1

I have a laravel 5.1 application where I use the default build in Authentication. I'm successfully logged in.

But when I try to use Auth::user() it always returns null. I'm using this code inside a controller. Also using it in a simple route without any custom code returns null.

Route::get('/', function () {
    dd(Auth::user());
});

Session driver is set to file.

Anyone any idea why it always returns null?



via Chebli Mohamed

Laravel 5.1 Auth not consistent

I am working on a project and did the Laravel 5.1 Authentication. I followed the Documentation. I only have one user, no registration.

Now, when I protect routes I do it this way:

Route::group(array('middleware' => 'auth', 'prefix' => '/admin'), function() 
{ ... }

Then the Login-Form comes back, i authenticate and it is working. But now, when I refresh the page (or go to other admin-pages) sometimes I am logged out and redirected to the login-form again, sometimes I get an "Whoops, looks like something went wrong.", and sometimes it is working for some requests.

I have no idea why and when it is happening. I followed this documentation: http://ift.tt/1NTLsZh

Did someone have the same problems? When I was working with Laravel 4.* everything was fine :( Thank you already!! gerti



via Chebli Mohamed

homestead laravel 5 : link Download file from storage

i am need hint link to download upload file, currently i am following this answer here is my code

Routes file :

Route::get('getDownload/{remind_letter}',
            ['as'=>'downloadData',
            'uses'=>'DockController@getDownload']);

Controller File :

  public function getDownload($remind_letter)
{

    $download = Dock::where('remind_letter','=',$remind_letter)->firstOrFail();
    $file =Storage::disk('local')->get($download->remind_letter);
    return (new response($file))->header('Content-Type', $entry->m1);
}

result file

<div class="row">
                <div class="form-group">
                    <div class="col-xs-5">
                    <label class="col-sm-7">Remind Letter :</label>
                    <input type="text" name="remind_letter" value="{{$getData->remind_letter}}">                    
                    </div>
                    <div><a href="{{ route('downloadData',$getData->remind_letter) }}">
                    <button class="btn btn-success btn-sm">Download</button></a></div>
                </div>
                </div>

and the result link dock.start/star/getDownload/home/vagrant/Code/dock/storage/app/25/JTK/2015/Renewal License Kaspersky/Moonarch Security/tmp/phpQaGzoD.pdf

but the link is always show up error 404 and i can't download file

FYI when upload file i am using storage_path() function



via Chebli Mohamed

Where did Laravel get references() method?

I've been stucked for quite an hour now as I am trying to find out where did Laravel 5.2 get the references() method code is shown below

Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('title');
        $table->text('body');
        $table->text('excerpt')->nullable();
        $table->timestamps();
        $table->timestamp('published_at');

        $table->foreign('user_id')->references('id')->on('users');
});

I can't seem to find the references() method in either \Illuminate\Database\Schema\Blueprint or Illuminate\Support\Fluent.

can anyone point me to where is the references() method in the above code can be found?

any help and tips would be great



via Chebli Mohamed

lundi 28 décembre 2015

auto logout in Laravel 5.1

I am new to Laravel 5.1, so I don't know how to log out a authenticated user after few minutes of inactivity. I read many sources about session.php that tells that 'lifetime' is responsible for the same. I set the values as:-

'lifetime' => 1, 'expire_on_close' => true,

but still my session is not getting expired and logging out after a minute. Even when i close the tab its not logging out. Please i need help in this. Is there a table to store session or what is the solution for this?



via Chebli Mohamed

Get selected value from a dropdown L-5.1 using JavaScript

I'm trying to get the selected value using Javascript and sending the value to the server side so as to process it using Laravel - PHP. This is ocde I've written so far, but I'm not getting it at the server side, is there anything I need to do more?

This is the blade file:

{!! Form::open(array('url' => 'created-products', 'method' => 'post'), array('id'=>'createproduct')) !!}
{!! Form::token() !!}

    @if(!Auth::check())
        <p><h3>Please login to create product</h3></p>
        @else
            <p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies, null, array('id'=>'companynameId')) !!} </p>
            <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
            <p>{!! Form::hidden('hiddenCompanyName', '', array('id'=>'selectedCompanyHidden')) !!}</p>
            <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

    @endif

    <script>
        var returnedCompany = document.getElementById("companynameId");
        var storedCompany = returnedCompany.options[returnedCompany.selectedIndex].value;

        var hiddenCompanyId = document.getElementsByName('hiddenCompanyName');
        document.createproduct.hiddenCompanyId.value = storedCompany;
        document.forms["createproduct"].submit();
    </script>
{!! Form::close() !!}

This is the function to get the value from the blade file:

private static function compareCompany(ProductRequest $productRequest){
        $companyPicked = $productRequest->hiddenCompanyName;
        $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
        $companies = new Company;
        if($companies->user_id === Auth::user()->id)
        {   
            foreach($listedCompanies as $company) {
                if($company->companyname === $companyPicked)
                {
                    return $company->id;
                } 
            }
        }
    }

This is the function to save it into the DB.

public function store(ProductRequest $productRequest)
{
   $product = new Product;
    $company = new Company;
   if($productRequest->isMethod('post')){

   $product->user_id     = Auth::user()->id;
   $product->company_id  = $this->compareCompany($productRequest);
   $product->companyname = $productRequest->companyname;
   $product->productname = $productRequest->productname;

   $product->save();
   return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
   }else{
        return redirect('company-create')->withErrors($productRequest)->withInput();
    }
}

Please help out. I've been on this for days. Appreciate.



via Chebli Mohamed

auth()->user() is null in Laravel 5.2

I just update the composer to Laravel 5.2 and not able to view password protected pages. Basically below line of code is not working.

auth()->user() 

Can somebody suggest why this is not working ?



via Chebli Mohamed

Tenanti "Undefined variable: Database"

I'm developing an application for multi tenant purpose, for this, I've used Orchestral/Tenanti but I'm experiencing the following problem.

I already performed some of the required steps for Multi Database Connection Setup.

  1. Configuration Tenant Driver for Multiple Database: on my tenanti.php
  2. Setting Default Database Connection: on my Tenant.php Middleware
  3. Definition of my Tenants Connection: on my config/database.php

The problem becomes on the Database Connection Resolver step. In my Middleware I'm defining the connection to be used (I don't post the code because is not relevant for Tenanti use) which is correctly setted.

My resolver code is:

public function boot()
    {
        Tenanti::connection('tenants', function (User $entity, array $template) {
            $template['database'] = "db_{$entity->getKey()}";
            return $template;
        });
    }

This code is located on my AppServiceProvider. But my database to be used, is not correctly setted from my Resolver, throwing the following error:

ErrorException in MySqlConnector.php line 110:
Undefined variable: database

Clearly the error means that database is no setted. Someone can help? Thanks in advance.



via Chebli Mohamed

Importing large CSV files in MySQL using Laravel

I have a csv file that can range from 50k to over 100k rows of data.

I'm currently using Laravel w/ Laravel Forge, MySQL, and Maatwebsite Laravel Excel package.

This is to be used by an end-user and not myself so I have created a simple form on my blade view as such:

{!! Form::open(
    array(
        'route' => 'import.store', 
        'class' => 'form',
        'id' => 'upload',
        'novalidate' => 'novalidate', 
        'files' => true)) !!}

    <div class="form-group">
        <h3>CSV Product Import</h3>
        {!! Form::file('upload_file', null, array('class' => 'file')) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Upload Products', array('class' => 'btn btn-success')) !!}
    </div>
{!! Form::close() !!}

This then stores the file on the server successfully and I'm now able to iterate through the results using something such as a foreach loop.

Now here are the issues I'm facing in chronological order and fixes/attempts: (10k rows test csv file)

  1. [issue] PHP times out.
  2. [remedy] Changed it to run asynchronously via a job command.
  3. [result] Imports up to 1500 rows.
  4. [issue] Server runs out of memory.
  5. [remedy] Added a swap drive of 1gb.
  6. [result] Imports up to 3000 rows.
  7. [issue] Server runs out of memory.
  8. [remedy] Turned on chunking results of 250 rows each chunk.
  9. [result] Imports up to 5000 rows.
  10. [issue] Server runs out of memory.
  11. [remedy] Removed some tranposing/joined tables logic.
  12. [result] Imports up to 7000 rows.

As you can see the results are marginal and nowhere near 50k, I can barely even make it near 10k.

I've read up and looked into possible suggestions such as:

  • Use a raw query to run Load Data Local Infile.
  • Split files before importing.
  • Store on server then have server split into files and have a cron process them.
  • Upgrade my 512mb DO droplet to 1gb as a last resort.

Going with load data local infile may not work because my header columns could change per file that's why I have logic to process/iterate through them.

Splitting files before importing is fine under 10k but for 50k or more? That would be highly impractical.

Store on server and then have the server split it and run them individually without troubling the end-user? Possibly but not even sure how to achieve this in PHP yet just only briefly read about that.

Also to note, my queue worker is set to timeout in 10000 seconds which is also very impractical and bad-practice but seems that was the only way it will keep running before memory takes a hit.

Now I can give-in and just upgrade the memory to 1gb but I feel at best it may jump me to 20k rows before it fails again. Something needs to process all these rows quickly and efficiently.

Lastly here is a glimpse of my table structure:

Inventory
+----+------------+-------------+-------+---------+
| id | profile_id | category_id |  sku  |  title  |
+----+------------+-------------+-------+---------+
|  1 |         50 |       51234 | mysku | mytitle |
+----+------------+-------------+-------+---------+

Profile
+----+---------------+
| id |     name      |
+----+---------------+
| 50 | myprofilename |
+----+---------------+

Category
+----+------------+--------+
| id | categoryId |  name  |
+----+------------+--------+
|  1 |      51234 | brakes |
+----+------------+--------+

Specifics
+----+---------------------+------------+-------+
| id | specificsCategoryId | categoryId | name  |
+----+---------------------+------------+-------+
|  1 |                  20 |      57357 | make  |
|  2 |                  20 |      57357 | model |
|  3 |                  20 |      57357 | year  |
+----+---------------------+------------+-------+

SpecificsValues
+----+-------------+-------+--------+
| id | inventoryId | name  | value  |
+----+-------------+-------+--------+
|  1 |           1 | make  | honda  |
|  2 |           1 | model | accord |
|  3 |           1 | year  | 1998   |
+----+-------------+-------+--------+

Full CSV Sample
+----+------------+-------------+-------+---------+-------+--------+------+
| id | profile_id | category_id |  sku  |  title  | make  | model  | year |
+----+------------+-------------+-------+---------+-------+--------+------+
|  1 |         50 |       51234 | mysku | mytitle | honda | accord | 1998 |
+----+------------+-------------+-------+---------+-------+--------+------+

So a quick run-through of my logic workflow as simple as possible would be:

  1. Load file into Maatwebsite/Laravel-Excel and iterate through a chunked loop
  2. Check if category_id and sku are empty else ignore and log error to an array.
  3. Lookup category_id and pull all relevant column fields from all related tables it uses and then if no null insert into the database.
  4. Generate a custom title using more logic using the fields available on the file.
  5. Rinse and repeat.
  6. Lastly export the errors array into a file and log it into a database for download to view errors at the end.

I hope someone can share with me some insight on some possible ideas on how I should tackle this while keeping in mind of using Laravel and also that it's not a simple upload I need to process and put into different related tables per line else I'd load data infile it all at once.

Thanks!



via Chebli Mohamed

laravel hasMany comments from a blog relationship

Im very new at using laravel so please be gentle. I have a blog, that has comments. Im using the hasMany to return the comments but I keep getting an empty array.

I have 2 tables; 1) Blog 2) Comments

The comments table tied the blog comment to the correct blog using a blog_id column in the table.

In my Blog model I am calling the following:

public function comments() {
    return $this->hasMany('App\Models\Comments', 'blog_id', 'id');
}

But I am getting an invalid argument for foreach. I have tried only using the frogein key, but still no luck.

As I said im new to using laravel and I hope you can understand where im coming from.

Thanks for any help!



via Chebli Mohamed

Error in Paypal authentication in Sandbox mode : Laravel 5.1

What I am doing ?

I have 2 Paypal Accounts. First belongs to my client and second belongs to me .On the first account I have created the Application and got the Sandbox credentials(ClientID and Secret).

Then I configured Paypal API in my Laravel 5.1 application and set the Sandbox credentials. So far everything is fine and I am able to reach the paypal page for the payment using the Sandbox credentials.

What's the problem ?

When I try to do the payment, it always says wrong credentials. Although I am able to login into my Paypal account but when I am on the Paypal payment page and tried to do authentication, I always get authentication failed error.

Question

Am I missing something ?



via Chebli Mohamed

Route Restriction base on Auth User Type

I have 3 kind of users

  • admin-super
  • admin
  • admin-readonly

I've created 3 Middlewares in /app/Http/Middleware I named them

  • AdminSuperMiddleware.php
  • AdminMiddleware.php
  • AdminReadonlyMiddleware.php

I've already registered them in /app/Http/Kernel.php as followed

    'admin'          => 'App\Http\Middleware\AdminMiddleware',
    'admin-super'    => 'App\Http\Middleware\AdminSuperMiddleware',
    'admin-readonly' => 'App\Http\Middleware\AdminReadOnlyMiddleware',


I've tried calling them in my routes.php

    $router->group(['middleware' => ['auth', 'admin-super'] ], function() {
        Route::get('account','AccountController@index');
        Route::post('account/store','AccountController@store');
        Route::post('/view-profile/logo/update', 'ProfileController@updateLogo');
    });

    $router->group(['middleware' => ['auth', 'admin'] ], function() {
        Route::get('account','AccountController@index');
        Route::post('account/store','AccountController@store');
    });

    $router->group(['middleware' => ['auth', 'admin-readonly'] ], function() {
        Route::get('account','AccountController@index');
    });


Result

When I log-in as user type == admin and go to :

http://localhost:8888/account

I kept getting 404.

Did I missing anything ?



via Chebli Mohamed

Models, Resource Controllers and Middleware in Laravel 5.1

I have several resources in Laravel 5.1 that are represented by models. The models all have account_id and user_id. There is a pivot table of user_account that represents the relationship between accounts and users.

I have my routes in routes.php that are resource controllers such as route.asset.

I am looking to create one Middleware for all of these controllers such I can do before => ['belongstoaccount']

And in that middleware it should check:

User belongs to the account in account.asset (I currently use ->contains() in the controllers.)

The account_id of the asset matches the account->id.

I want to make one middleware for all these assets. Is this even possible? Should I be looking in $request for this information?

Thank you for any guidance,

Josh



via Chebli Mohamed

Laravel 5.1 - How to get not attached pivot registers for add

I am doing a CRUD with Laravel 5.1. When I click the add button, a form with a select box Is shown (the controller sends all the data correctly). All works fine, but I want to improve the form not showing elements attached to the model.

Example: 2 models, User and Role, with a Relationship Many to Many. My controller gets all the roles attachedto the current user EXCEPT which are already attached.

Any idea how to get this?



via Chebli Mohamed

How to handle PDOException in Laravel 5

I've modified Exceptions/Handler.php to:

    <?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler {

    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
    'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {

        if($e instanceof NotFoundHttpException)
        {
            return response()->view('errors/404');
        }

        elseif ($e instanceof ErrorException) {
            return response()->view('errors/404');
        }

        elseif ($e instanceof ModelNotFoundException) {
            return response()->view('error_log(message)ors/404');
        }

        elseif($e instanceof PDOException)
        {
            return Redirect::to('install.php');
        }

        elseif($e instanceof QueryException)
        {
            return Redirect::to('install.php');
        }

        else return response()->view('errors/error');


    }

trying to redirect to installation whenever application makes PDOException, but I'm just getting general error view (errors/error - from the last line of the code above).

Is there a way to cach specifically PDOException error?



via Chebli Mohamed

How to use checkbox groups in Laravel5.1

Here is Error

Creating default object from empty value

Here is a part of view

<div class="form-group">
    <label class="col-md-4 control-label">職種</label>
    <div class="col-md-6">
       <div class="col-md-6">
           <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="アカウント/企画営業" {{ $data->checkedJob('アカウント/企画営業') }}>
               アカウント/企画営業
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="プロジェクトマネージャー/プロデューサー" {{ $data->checkedJob('プロジェクトマネージャー/プロデューサー') }}>
               プロジェクトマネージャー/プロデューサー
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="Webディレクター" {{ $data->checkedJob('Webディレクター') }}>
               Webディレクター
           </label>
       <label class="checkbox-inline">
               <input type="checkbox" name="job[]" value="Webマーケター" {{ $data->checkedJob('Webマーケター') }}>
               Webマーケター
           </label>
       </div>
    </div>
</div>
<div class="form-group">
    <label class="col-md-4 control-label">スキル</label>
    <div class="col-md-6">
      <!-- タブ・メニュー -->
      <ul class="nav nav-tabs">
        <li class="active"><a href="#sampleContentA" data-toggle="tab">エンジニア・デザイナー</a></li>
        <li><a href="#sampleContentB" data-toggle="tab">ビジネス</a></li>
      </ul>
      <!-- タブ内容 -->
      <div class="tab-content">
        <div class="tab-pane active" id="sampleContentA">
          <p>Web制作</p>
           <input type="checkbox" name="tech_skill[]" value="XHTML" {{ $data->checkedTech('XHTML') }}>XHTML
           <input type="checkbox" name="tech_skill[]" value="HTML" {{ $data->checkedTech('HTML') }}>HTML
           <input type="checkbox" name="tech_skill[]" value="CSS" {{ $data->checkedTech('CSS') }}>CSS
        </div>

        <div class="tab-pane" id="sampleContentB">
          <p>Webマーケティング</p>
           <input type="checkbox" name="biz_skill[]" value="Webディレクション" {{ $data->checkedBiz('Webディレクション') }}>Webディレクション
           <input type="checkbox" name="biz_skill[]" value="GoogleAdSense" {{ $data->checkedBiz('Google AdSense') }}>Google AdSense

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

Here is a part of ProfileController

public function postUpdate(Request $request)
{
    // バリデーション
    $inputs = $request->all();

    // ルール
    $rules = [
        'tw_id'=>'max:100',
        'fb_id'=>'max:100',
        'url'=>'url|max:200',
        'comment'=>'max:500'
    ];

    $message = [
        'tw_id'=>'TwitterIDは100文字以内で記入してください。',
        'fb_id'=>'FacebookIDは100文字以内で記入してください。',
        'url.url' => 'URLは正しい形式で指定してください。',
        'url.max' => 'URLは200文字以内で指定してください。',
        'comment.max' => 'コメントは500文字以内で記入してください。',
    ];

    $validator = \Validator::make($inputs,$rules,$message);

    if($validator->fails()){
      return redirect()->back()->withErrors($validator->errors())->withInput();
    }

    // ユーザー情報取得
    $user = Auth::user();
    $name = $user->name;

    // Profileテーブルのデータ取得
    $data = Profile::where('name','=',$name)->first();

    $job = $request->job;
    $jobImp = implode(',',$job);
    $data->job = $jobImp;

    $tech = $request->tech_skill;
    $techImp = implode(',',$tech);
    $date->tech_skill = $techImp;

    $biz = $request->biz_skill;
    $bizImp = implode(',',$biz);
    $date->biz_skill = $bizImp;

    $data->tw_id = $request->tw_id;
    $data->fb_id = $request->fb_id;
    $data->url = $request->url;
    $data->comment = $request->comment;

    $data->save();

    \Session::flash('flash_message', 'プロフィール情報を更新しました!');

    return redirect()->to('mypage');
}

Here is a part of Profile

Schema::create('profile', function (Blueprint $table) {
      $table->increments('id');
      $table->rememberToken();
      $table->timestamps();
      $table->string('name')->foreign('users')->on('name');
      $table->text('profile_image_name',200);
      $table->text('job',50)->nullable();
      $table->text('tech_skill',500)->nullable();
      $table->text('biz_skill',500)->nullable();
      $table->string('tw_id',100)->nullable();
      $table->string('fb_id',100)->nullable();
      $table->string('url',200)->nullable();
      $table->string('comment',500)->nullable();
  });

When i use only checkbox group(job[]),i have no errors with in my code.

What is wrong with this code? How do i use checkbox groups in Laravel5.1?



via Chebli Mohamed

Firing Event on particular queue

I am using laravel 5.1 and I am creating event which I want it to be queued,but i don't want it to be queued on the default queue. Is there any way to do it?



via Chebli Mohamed

Laravel 5.1 : Looking for ajax script to validate form on modal dialog

I'm newbie in ajax ^^', so I'm looking for an ajax script to validate my form on a modal dialog using laravel 5.1 rules, especially unique rule on create and update. Please any one would help me :)



via Chebli Mohamed

url not found error in laravel

I am using Laravel 5 with a new version of apache on ubuntu and when I try to access the page: localhost it works and if I try localhost/index.php/my_page it works but if I try localhost/my_page, it doesnt. So from searching other questions I guess my problem lies in the .htaccess file.

As per suggestions I saw online I added the rewriteBase and Options +FollowSymLinks to my .htaccess in laravel/public:

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

      Options +FollowSymLinks
      RewriteEngine On
      RewriteBase /repos/kenrose/public

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

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

and this is what my apache2.conf file looks

    <Directory /repos/kenrose>
       Options Indexes FollowSymLinks
       AllowOverride All
       Require all granted
    </Directory>

I've taken all the suggestions i've found about this issue. What is the problem?



via Chebli Mohamed

Laravel Schema::drop($table) return value

I was just wondering if I use drop() method in Laravel Eloquent like say,

    Schema::drop('users')

what will be the return value of it ? Though I can use hasTable() method after drop() method to check table existence but I was just wondering if we can get it directly from return value ?

In laravel api Blueprintclass I can see it's mentioned as Return Value - Fluent. But I don't know what is the meaning of it ? Can anyone help ?

Thanks in advance,

Sambhav



via Chebli Mohamed

One url/route two different controller laravel 5 based on user logged in or not

How can I load different controllers based on user logged in or not ?

What I'm trying to do is

// in app/Http/routes.php

Route::get('/', [
    'uses' => 'App\Http\Controllers\HomeController@index',
]);


// modules/Lesson/Http/routes.ph

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

    Route::get('/', [
        'uses' => 'Modules\Lesson\Http\Controllers\DashboardController@index',
    ]);
});

So when user logged in, it shows DashboardController@index, otherwise HomeController@index

But it always loading /login form when user not signed in.

Is there any way to achieve this?

I have seen following link Laravel 5 Entrust one route - load different controller based on Role. But i can't do like that since module is optional



via Chebli Mohamed

How do I make a Laravel 5.1 ACL work with a client and admin panel?

My situation: Using Laravel 5.1, I want to use it's built in ACL features. Challenge: My website has a Admin and a Client side to it. On top of that, the database structure for each is very different and the Control Panel for Admin and Client is very different.

How do I go about implementing ACL with this?

Note - I have subfolders for each part of the website (one folder for client side, one folder for admin, one folder for front-end pages).

Is this even possible to build using Laravel's built-in ACL system? or should I make my own in my situation? Thank you.



via Chebli Mohamed

dimanche 27 décembre 2015

Get the ID of a selected value from a dropdown selectbox using Laravel 5.1

I've been on this for a while, what I want to do is to get the id of the selected value from a select box. Using this snippet, it doesn't get the id and I wonder why. I'm confused what what could be wrong

This code is to get the id of the selected value:

private static function compareCompany(ProductRequest $productRequest){
            $companyPicked = $productRequest->companyname;
            $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
            $companies = new Company;
            if($companies->user_id === Auth::user()->id)
            {   
                foreach($listedCompanies as $company) {
                    if($company->companyname === $companyPicked)
                    {
                        return $company->id;
                    } 
                }
            }
        }

This is to create a new product using the id returned for a company

public function store(ProductRequest $productRequest)
    {
       $product = new Product;
        $company = new Company;
       if($productRequest->isMethod('post')){

       $product->user_id     = Auth::user()->id;
       $product->company_id  = $this->compareCompany($productRequest);
       $product->companyname = $productRequest->companyname;
       $product->productname = $productRequest->productname;

       $product->save();
       return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
       }else{
            return redirect('company-create')->withErrors($productRequest)->withInput();
        }
    }

THis is the view:

<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>

THis is the code used in binding the returned value to the view:

public function create()
    {

      $listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'companyname')->toArray();
        return view('product.create')
        ->with('listCompanies', $listCompanies);
    }



via Chebli Mohamed