ken4ward

ken4ward

Member Since 3 Years Ago

Experience Points 1,390
Experience
Level
Lessons Completed 1
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

11 Jan
1 week ago

ken4ward started a new conversation Querying A Single User From Lumen API

Kindly help me on how to write the api route on querying a single user. I have the one that returns all the records in the database.

This is the route $api->group([ 'namespace' => 'App\Http\Controllers', 'middleware' => ['auth:api', 'cors'] ], function ($api) { $api->get( 'users', '[email protected]', ); });

This is the controller public function showOne( $id ) { $user = $this->userRepository->getById( $id ); $response = $this->response->item( $user, new Transformer() ); return $response; }

ken4ward left a reply on Object Of Class App\\Repository\\UserRepository Could Not Be Converted To String

@JLRDW - Whenever I tried voting the right answer it returns a 404 error page.

ken4ward left a reply on Object Of Class App\\Repository\\UserRepository Could Not Be Converted To String

I'm very grateful for this. Solved it brilliantly.

ken4ward started a new conversation Object Of Class App\\Repository\\UserRepository Could Not Be Converted To String

I am presently using the repository but kept getting the error

UserRepository class

    {
        $users = User::all();
        return $users;
    }```

Object of class App\Repository\UserRepository could not be converted to string.

THis is the controller class
```public function show()
    {
        $user = $this->$userRepository->getAll();
        $response = $this->response->item($user, new UserTransformer());
    }```

Kindly help.
23 Nov
2 years ago

ken4ward started a new conversation How To Query Multiple Tables For A Full Text Search?

While working on a search function on a project, I'm poised with how to query multiple models via a function. The one i have working now only queries a model

        $searchedSongs = '';
       if($request->has('search')){
          
          $searchedSongs = Songs::search($request->input('search'))->get();
       }
       return view('search.results')->with('searchedSongs', $searchedSongs);
    }```

ken4ward left a reply on Laravel Scout And Elasticsearch Returns Error When Searching.

Thanks. You saved my day. Appreciate. God bless.

ken4ward started a new conversation Laravel Scout And Elasticsearch Returns Error When Searching.

am trying to run Laravel scout with Elasticsearch. Elasticsearch is running on: http://localhost:9200/ and Laravel on : http://localhost:8000/ Everything was going on smoothly until I try using tinker to query the imported models, I am getting this error:

Imported [App\Albums] models up to ID: 2
All [App\Albums] records have been imported.
C:\xampp\htdocs\blacapollo>php artisan tinker
Psy Shell v0.7.2 (PHP 7.0.8 ΓÇö cli) by Justin Hileman
>>> App/Albums::search('come and')->get();
PHP Fatal error:  Class 'Albums' not found in eval()'d code on line 1
>>>``` 
06 Apr
2 years ago

ken4ward started a new conversation Save New Model Record In The Db

I am trying to save this record but it keeps returning the page without actually performing the saving. No error message is sent as response and the chrome debug console gives no idea as to what s going on, so I'm left to guess and your professional advice on how to solve this riddle.

This is the function to perform the actual saving in the DB.

public function returnObjects(BidWinnerRequest $bidWinnerRequest){
        $product_id                             = $bidWinnerRequest->product_id;
        $bidding_table_id                       = $bidWinnerRequest->bidding_table_id;

        if($bidWinnerRequest->isMethod('post')){
            $bidWinner = new BidWinner;
            $bidWinner->product_id       = $product_id;
            $bidWinner->bidding_table_id = $bidding_table_id;

            $bidWinner->actual_price                = floatval(4567);
            $bidWinner->offered_price_price         = floatval(112233);;

            $bidWinner->save();
            return redirect()->route('biddingCommentView')->with('message', 'Your question has been posted.');
        }
    }

This is the function returning the page, appended are the models that matches the query. To each model a button is attached, so depending on the button selected the corresponding model is returned.

public function show($id)
    {
        $biddingComments = BiddingComments::findOrFail($id);
        return view('buyers.show')->with('biddingComments', $biddingComments);
    }

This is the page This is the route I'm using for the posting

Route::post('post/to/input/save', array('before'=>'csrf', 'uses'=>'MyBuyers@returnObjects'));

This is the page that displays the selected model. This is the page I will make a selection from. It is from this I want to save the records into the database.

{!! Form::open(array('url' => 'post/to/input/save', 'method' => 'post')) !!}
    {!! Form::token() !!}

                <div align="center" background-color="white"><TABLE>
                      <TH>FIELDS</TH><TH>NAMES</TH>
                      <TR><TD><B>PRICE </B></TD><TD>{!! $biddingComments->price !!} (US Dollars)</TD></TR>
                      <TR><TD><B>DOCUMENTS TO UPLOAD</B></TD><TD>{!! $biddingComments->documentPerSector !!}</TD></TR>
                      <TR><TD><B>PAYMENT METHOD</B></TD><TD>{!! $biddingComments->payment_methods !!}</TD></TR>          
                      {!! Form::hidden('bidding_table_id', $biddingComments->id) !!}
                      {!! Form::hidden('product_id', $biddingComments->product_id) !!}
                      <TR><TD><B>{!! Form::submit('SUBMIT') !!}</B></TD><TD></TD></TR>

                </TABLE>
            </div>
  @stop
30 Mar
2 years ago

ken4ward started a new conversation Trying To Display Image In Laravel 5.1 Using Dropzone

I am trying to display the image from the file path but it's seeing a different thing entirely, I'm vague of what to do. I am using dropzone. The images are stored in this directory laravel/public/gallery/images. so the url is thus: http://localhost:port/gallery/images. The images are saved in the db successfully but displaying them is an issue. This is the code to display:

<TR><TD>

                    <DIV class="row">
                      <DIV class="col-md-12">
                        <DIV id="gallery-images">
                            <ul>
                                @foreach($productVerificationValidation->productDocumentUpload as $productDocument)
                                  <li>
                                      <a href="{{url($productDocument->file_path)}}./.{{$productDocument->file_name}}" target="_blank">
                                        <img src="{{url($productDocument->file_path)}}">
                                      </a>
                                  </li>
                                @endforeach
                            </ul>
                        </DIV>
                      </DIV>
                    </DIV>

                  </TD></TR>

This is the controller to display the view:

   public function viewUploadedDocuments($id=null){
            $productVerificationValidation = ProductVerificationValidation::findOrFail($id);
            return view('product.verification-validation.viewDocuments')->with('productVerificationValidation', $productVerificationValidation);
}

To my surprise when i check the console on Chrome, instead of getting the properties of the images it returns wrong properties as displayed on the screenshot: wrong properties assigned to an image but the db record has a different property as displayed on the screenshot: db properties different from what's displayed on console. what wrong am I to make right, Please help out.

29 Mar
2 years ago

ken4ward started a new conversation Laravel Save Image Using Dropzone.js Into MySQL

I'm just trying out dropzone for the first time and would need assistance to set it up. I am getting error 500 thus:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

This is the controller:

public function storeDocument(Request $request){

         $file = $request->file('file');
         $fileName = uniqid().$file->getClientOriginalName();
         $file->move('gallery/images', $fileName);

         $productVerificationValidation = ProductVerificationValidation::findOrFail($request->productDocumentNameId);
         $documentsUploaded = $productVerificationValidation->productDocumentUpload()->create([
                'gallery_id'    =>  $request->productDocumentNameId,
                'user_id'       =>  Auth::user()->id,
                'company_id'    =>  $request->company_id,
                'product_id'    =>  $request->product_id,
                'file_name'     =>  $fileName,
                'file_size'     =>  $file->getClientSize(),
                'file_mime'     =>  $file->getClientMimeType(),
                'file_path'     =>  'gallery/images'. $fileName
            ]);
    }

This is the route to store the image credentials:

Route::post('product/document/upload/save', array('before'=>'csrf', 'uses'=>'ProductVerificationValidationController@storeDocument'));

This is the form for Dropzone:

<form action="{{url('product/document/upload/save' )}}" 
                        class="dropzone  first-input-div" id="addImages">{{csrf_field()}} 
                        {!!Form::hidden('productDocumentNameId', $productVerificationValidation->id)!!}
                        {!!Form::hidden('product_id', $productVerificationValidation->product_id)!!}
                        {!!Form::hidden('company_id', $productVerificationValidation->company_id)!!}</form>

This is the model setup:

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

I'm yet to understand what I need to do right. Please help out.

26 Mar
2 years ago

ken4ward started a new conversation Uncaught TypeError: Cannot Read Property 'submit' Of Undefined

I have this javascript snippet that was working witout error before it began to raise issue of recent. This is the code:

function doSomething(){
  var myselect = document.getElementById("selectOpt");
  document.getElementById("selectedProductHiddenId").value = myselect.options[myselect.selectedIndex].value;
  document.getElementById("selectedCompanyHiddenId").value = myselect.options[myselect.selectedIndex].text;
  alert(document.getElementById("selectedCompanyHiddenId").value);
  alert(document.getElementById("selectedProductHiddenId").value);
  this.form.submit();
}

This is the error message:

Uncaught TypeError: Cannot read property 'submit' of undefined

ken4ward left a reply on Model Not Saving

Prez, Words aren't enough to appreciate your support. It's simple mistake of changing the naming convention and not changing it in the request form. i was formally using role before changing it to user_role_process. Thanks a bunch.

ken4ward left a reply on Model Not Saving

Thanks, Prez. I have added dd before and, afterwards added it after save() metod, it still did not save. it's giving no error message.

ken4ward started a new conversation Model Not Saving

I cannot understand why this model is not saving. I have triple check all and couldn't find what is missing. What's to be fixed? Please help out. This is the controller:

public function store(ProductRoleProcedurePaymentRequest $productRoleProcedurePaymentRequest)
    {
        $hiddenProductId = $productRoleProcedurePaymentRequest->hiddenProductId;

        if($productRoleProcedurePaymentRequest->isMethod('post')) {
            $productRoleProcedurePayment                     = ProductRoleProcedurePayment::firstOrNew(array('product_id'=>$hiddenProductId));
            $productRoleProcedurePayment->product_id         = $productRoleProcedurePaymentRequest->hiddenProductId;
            $productRoleProcedurePayment->productname        = $this->SelectProdutById($productRoleProcedurePaymentRequest);
            $productRoleProcedurePayment->user_id            = Auth::user()->id;
            $productRoleProcedurePayment->company_id         = $this->SelectCompanyId($productRoleProcedurePaymentRequest);
            $productRoleProcedurePayment->user_role_process  = $productRoleProcedurePaymentRequest->user_role_process;
            $productRoleProcedurePayment->payment_methods    = $productRoleProcedurePaymentRequest->payment_methods;
            $productRoleProcedurePayment->procedure          = $productRoleProcedurePaymentRequest->procedure;
            
            $productRoleProcedurePayment->save();
            return redirect()->route('')->with('message', 'Your question has been posted.');
        }else{
                return redirect()->route('productRoleProcedurePaymentIndex')->withErrors($productRoleProcedurePaymentRequest)->withInput();
        }
    }

This is the blade:

 @section('sidebar')
   {!! Form::open(array('url' => 'product/role/procedure/payment/save', 'method' => 'post')) !!}
    {!! Form::token() !!}
        <div>
          <div>
            <div>
              <div class="first-contact-div" >
                    <DIV align="center"><SPAN class="div-header">PRODUCT SPECIFICATION</SPAN></DIV>
                  <TABLE class="">
                    <TH>FIELD</TH><TH>DESCRIPTION</TH>
            <TR><TD><div>{!! Form::select('productname', array('-1' => 'Select a Product') + $listProducts, null, array('class'=>'mid first-input-div select2', 'id'=>'selectOpt', 'onchange'=>'doSomething();', 'onfocus'=>'this.selectedIndex = -1;')) !!} </div></TD><TD><div></div></TD></TR>       

            <TR><TD><div>
              <select name="role" id="role" class="select2 mid first-input-select" placeholder="Role">
                    <option></option>
                    <optgroup label="Government">
                         <option value="Score">Score </option>
                    </optgroup>
                    <optgroup label="Others">
                         <option value="Private">Private</option>
                         <option value="Independent">Independent</option>
                         <option value="Agent">Agent</option>
                    </optgroup>
              </select>
            </div></TD><TD></TD></TR>
            <TR><TD><div>
              <select name="process" id="process" class="select2 mid first-input-select" placeholder="Process">
                    <option></option>
                    <option value="Tanker ">Tanker</option>
                    <option value="Lorry Ride">Lorry Ride</option>
             </select>
            </div></TD><TD></TD></TR>
            <TR><TD><div>
              <select name="mygoals" id="mygoals" class="select2 mid first-input-div" placeholder="My Goals">
                    <option></option>
                    <option value="Wire">Wire</option>
                    <option value="Letter">Letter</option>
                    <option value="Online">Online</option>
              </select>

12 Mar
2 years ago

ken4ward left a reply on Get Js Value In Laravel Controller

Please could you enlighten me on what you mean by dd?

ken4ward started a new conversation Get Js Value In Laravel Controller

How do I get the js value in Laravel controller. I want to pass the value from the hidden fields to be saved in the db, but to my surprise it saves empty records for these fields. When I logged the values on the console, I am seeing it but it is not passed as the value to the controller. What better way am I to handle this?

 public function store(UserContactRequest $userContactRequest)
    {
        $phone           = $userContactRequest->phone_output;
         if(Auth::user()) {
            if($userContactRequest->isMethod('post')) {
               $userContact = UserContact::firstOrNew(array('user_id'=>Auth::user()->id));
                $userContact->phone     = $phone;
                $userContact->save();
                return redirect()->route('userContactIndex')->with('message', 'Your question has been posted.');
            }else{
                 return redirect('user/contact/create')->withErrors($userContactRequest)->withInput();
            }
         }
    }

This is the blade file

<TH>FIELD</TH><TH>DECRIPTION</TH>
                    <input type="hidden" name="phone_output" id="phone_output">
                    <TR><TD><div>{!! Form::tel('phone', Input::old('phone'), ['class'=>'mid first-input-div', 'placeholder'=>'8023472436', 'id'=>'phone']) !!}</div></TD><TD class="font-description"><SPAN id="errNm1"><STRONG><I>FIRSTNAME</I></STRONG></SPAN> field requests the input of your surname or family name. Only <SPAN><STRONG><I>alphabets</I></STRONG></SPAN> are accepted as valid inputs. </TD></TR>

THis is the js file:

$("#phone").intlTelInput();

var input = $("#phone"),
  output = $("#phone_output");

input.intlTelInput({
  nationalMode: true,
  utilsScript: "http://localhost:88/build/js/utils.js" // just for formatting/placeholders etc
});

// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
  var intlNumber = input.intlTelInput("getNumber");
  if (intlNumber) {
    output.text("International: " + intlNumber);
    console.log(intlNumber);
  } else {
    output.text("Please enter a number below");
  }
});
11 Mar
2 years ago

ken4ward started a new conversation How To Make An Image Link In Laravel 5.1

How to make an image link in Laravel 5.1

<div class="first-div-inner"><img style='height: 100%; width: 100%; object-fit: contain' src="{!! asset('images/add.png') !!}"/></div>

I have a route that I want to point to when an image is clicked. Using text, it's simple, but I have not been able to find away around using image as a link

If it is text, it'll be thus

{!! Html::linkRoute('myRouteName', 'text to display') !!}

How do I substitute the 'text to display' with an image? Thanks.

25 Feb
2 years ago

ken4ward started a new conversation Allow A User To Bid On A Product Only Once Using Laravel 5.1

Simple logic required to get this finished, I pray the help of an expert. I'm presently trying a way out to implement a restriction on a bidding website I'm developing, the simplicity is this: a user cannot bid on a product more than once. If the user clicks on the product again, he should be prompted with a response page noting the user of having previously bid on the product,

This is the blade form:


            @if(Auth::user()->id === $product->user_id)
                <p>Sorry, you posted this product, you cannot quote on it.</p>

            @else
            <p>{!! Form::label('Higest Price') !!}</p>
            <p>{!! Form::number('price', Input::old('price')) !!}</p>
            <p>{!! Form::textarea('comments', Input::old('comments')) !!}</p>
            <p>{!! Form::hidden('product_id', $product->id) !!}</p>
            <p>{!! Form::hidden('company_id', $product->company_id) !!}</p>
            <p>{!! Form::hidden('user_id', $product->user_id) !!}</p>

            <p>{!! Form::submit('ADD QUOTE') !!}</p>
        @endif
        {!! Form::close() !!} ```

This is the controller:
``` public function store(BiddingCommentRequest $biddingCommentRequest)
    {
        $biddingComments = new BiddingComments;
        $product_id = $biddingCommentRequest->product_id;
        $AuthUserBidder = Auth::user()->id;
        $bidderCommented = BiddingComments::all();

        if($biddingCommentRequest->isMethod('post')){
            foreach ($bidderCommented as $key => $commentedBidder) {
               if(!count($commentedBidder->id) > 0)
               {
                    $biddingComments->bidder_id  = $AuthUserBidder;
                    $biddingComments->product_id = $product_id;
                    $biddingComments->company_id = $biddingCommentRequest->company_id;
                    $biddingComments->user_id    = $biddingCommentRequest->user_id;
                    $biddingComments->comments   = $biddingCommentRequest->comments;
                    $biddingComments->price      = $biddingCommentRequest->price;
                    $biddingComments->save();
                     return redirect()->route('biddingCommentView', $product_id)->with('message', 'Your question has been posted.');
               }elseif(($AuthUserBidder == $commentedBidder->bidder_id) && ($product_id == $commentedBidder->product_id))
               {
                    return redirect()->route('productindex')->with('message', 'Your question has been posted.');
               }else
               {
                    $biddingComments->bidder_id  = $AuthUserBidder;
                    $biddingComments->product_id = $product_id;
                    $biddingComments->company_id = $biddingCommentRequest->company_id;
                    $biddingComments->user_id    = $biddingCommentRequest->user_id;
                    $biddingComments->comments   = $biddingCommentRequest->comments;
                    $biddingComments->price      = $biddingCommentRequest->price;
                    $biddingComments->save();
                     return redirect()->route('biddingCommentView', $product_id)->with('message', 'Your question has been posted.');
                }
            }
        }
    }

It's not adding the restriction. It allows user to keep quoting on a product over and over again. Kindly help, please.

24 Feb
2 years ago

ken4ward left a reply on How To Add A Facade In Laravel 5.0

Hope my answer would still be relevant since this thread seems long dated. To use Twilio via Aloha plugin for Laravel, do thus: Run on your cmd: composer require aloha/twilio Next add the provider to your config/app.php file like this: Aloha\Twilio\Support\Laravel\ServiceProvider::class,

Add the facade: 'Twilio' => Aloha\Twilio\Support\Laravel\Facade::class,

Doing these would give you a smooth ride. The problem could be caused because Laravel is fast evolving, so implementation is different from version to version.

09 Jan
3 years ago

ken4ward started a new conversation Typeahead Not Working With Laravel 5.1

I wonder why this is not pulling records from the database. I have been on this for days. All I want to do is use typeahead to select matching record from the db. When a user enters a character, the matching records should be displayed so that the user can select the relevant value. I hope a kind heart would help me resolve this.

THis is the controller:

public function SelectLocationPlaces(UserAdressRequest $userAdressRequest)
        {
             if($userAdressRequest->isMethod('post'))
             {
                if($userAdressRequest->has('query'))
                {
                    $query = $userAdressRequest->get('query');
                    $locationPlaces = LocationPlaces::where('name', 'like', "%{$query}%")->toArray();
                    return json_encode($locationPlaces);
                }
             }
        }

This is the blade form:

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

    <link href="{!! asset('bootstrap/css/bootstrap.css') !!}" media="all" rel="stylesheet" type="text/css" />
    <link href="{!! asset('css/style.css') !!}" media="all" rel="stylesheet" type="text/css" />
    <!--<link rel="stylesheet" type="text/css" href="style.css">-->
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>

<p>{!! Form::select('countries', array('-1' => 'Select a Country') + $listedCountries) !!} </p>
<div class='well'>
    <p>{!! Form::text('query', '', array('id'=>'typeahead', 'data-provider'=>'typeahead')) !!}</p>
</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="{!! asset('bootstrap/js/bootstrap.js') !!}" type="text/javascript" />

    <script>
        $(function(){
                $('#typeahead').typeahead({
                    source: function(query, process){
                        $.ajax({
                            url: '{{ url('json/redirects/') }}',
                            type: 'POST',
                            data: 'query=' +query,
                            dataType: 'JSON',
                            async: true,
                            success: function(data){
                                process(data);
                            }
                        });
                    }
                });
            });
    </script>

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

This is the route:

Route::post('json/redirects', array('before'=>'csrf', 'uses'=>'UserAddressController@SelectLocationPlaces
29 Dec
3 years ago

ken4ward left a reply on Get Selected Value From A Dropdown L-5.1 Using JavaScript

Truly speaking, the JavaScript variable does not receive any value. I'm surprised it doesn't. Why? Any reason?

ken4ward started a new conversation 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.

27 Dec
3 years ago

ken4ward left a reply on Get Selected Value From A Dropdown L-5.1

I would appreciate if you can help me out with the snippet.

26 Dec
3 years ago

ken4ward started a new conversation Get Selected Value From A Dropdown L-5.1

How to get selected value from a dropdown box and add it to a to a hidden field.

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

ken4ward started a new conversation Dropdowb Selecting Id As Value Not Text

I'm appalled by this, though it should be a brush-up for Laravel experts. I'm using this code to populate a dropdown select box, which populates it very well, but when I select a value from the dropdown select box instead of giving me the value it gives the id, where do I need to improve?

This is the code used in populating the select box dropdown:

public static function ReturnComanyPerUser()
     {
        return static::where('user_id', '=', Auth::user()->id)->orderBy('companyname')->lists('companyname', 'id');
     }

This is the binding to the dropdown:

public function create()
    {
        return view('product.create')->with('companyforproduct', Company::ReturnComanyPerUser());
    }

This is the blade page where the dropdown is:

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

    <p>{!! Form::select('companyname', $companyforproduct) !!} </p>
    <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
    <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

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

How do I get the value not id? When I select from dropdown it gives me the id of the value. I get a display like this:

Company name  product name
        2               fish    
21 Dec
3 years ago

ken4ward left a reply on Unable To Delete When Using Soft Delete

Finally, I got it solved by God's grace. The primary problem was that I was trying to retrieve the the id of the company at runtime which was not available. To my surprise, Laravel already cares for the thing I was trying to do manually, all I did is t pass in the a generic id, and laravel figured t out which company I;m trying to query, and does the job. Very efficient, Laravel.

public function destroy($id)
    {
        $company = Company::findOrFail($id);
        if(!$company->user_id === Auth::user()->id)
        {
            return redirect()->route('companyindex')->with('message', 'Sorry, you cannot delete this company');
        }else{
            $company->delete();
            return redirect()->route('companyindex')->with('message', 'Company successfully deleted.');
        }
    }

ken4ward left a reply on Unable To Delete When Using Soft Delete

I think I've gotten a clue of what could be the problem. I tried getting the authenticated user that logged in but returned null, even after logging in. After getting this, that session weren't maintained for a logged in user, I decided to google how Laravel maintains session for a logged in user, from the documentation, I got to understand that the "remember me" checkbox is very important to achieve this, and a clue of how to implement it is documented for those not using custom login, since mine is custom login, how do I implement the remember me, so that session of logged in user can be maintained? I checked the database and got to understand that even if a user is logged, the remember_token is always null. I need your expert support on this. Thanks. Appreciate.

20 Dec
3 years ago

ken4ward left a reply on Unable To Delete When Using Soft Delete

Do you notice anything with the route, is it suppose to be like this? Is it the delete keyword I'm to use?

Route::delete('deletecompany/{id}', array('as'=>'deleteCompany', 'uses'=>'CompanyController@destroy'));

ken4ward left a reply on Unable To Delete When Using Soft Delete

No. still don't. I'm yet to understand where the clause is.

19 Dec
3 years ago

ken4ward left a reply on Unable To Delete When Using Soft Delete

private function companyBelongsToUser($id){
        $company = Company::find($id);
        if($company->user_id == Auth::user()->id){
            return true;
        }
        return false;
    }

This is the function to check if the user is the expected user. Thanks I appreciate

ken4ward started a new conversation Unable To Delete When Using Soft Delete

Trying out softdelete and I'm yet to understand what is wrong with the code. Whenever I try deleting. it doesn't, it throws back the page at me. I know for experts on this forum, it'll be very easy to see the missing link. Kindly help out.

This is the controller for confirmation page before deleting:

public function deleteView($id)
    {
        $company = Company::find($id);
        return view('company.show')->with('company', $company);
    }

This is the view to confirm before deleting:

@extends('layouts.member')

    @section('content')
        {!! Form::open(array('action'=> array('CompanyController@destroy', $company->id, '_method'=>'delete'))) !!}
        {!! Form::token() !!}

            <p>{!! $company->companyname !!}</p>
            <p>{!! $company->companyaddress !!}</p>
            </p>{!! $company->country !!}</p>
            <p>{!! $company->state !!}</p>
            <p>{!! $company->email !!}</p>
            <p>{!! $company->phone !!}</p>
            <p>{!! $company->website !!}</p>
            <p>{!! $company->companytype !!}</p>

            {!! Form::hidden('company_id', $company->id) !!}
            <p>{!! Form::submit('DELETE') !!}</p>
        {!! Form::close() !!}
    @stop

This is the convtroller to effect deleting:

public function destroy(CompanyRequest $companyRequest)
    {
        $company_id = $companyRequest->company_id;
        if(!$this->companyBelongsToUser($company_id))
        {
            return redirect()->route('companyindex', $company_id)->with('message', 'Sorry, yuo cannot delete this company');
        }else
        {
            $company = Company::findOrFail($company_id);

            $company->companyname    = $companyRequest->companyname;
            $company->companyaddress = $companyRequest->companyaddress;
            $company->country        = $companyRequest->country;
            $company->state          = $companyRequest->state;
            $company->email          = $companyRequest->email;
            $company->phone          = $companyRequest->phone;
            $company->website        = $companyRequest->website;
            $company->companytype    = $companyRequest->companytype;
            
            $company->delete();
            return redirect()->route('companyindex', $company_id)->with('message', 'Company deleted successfully');
        }
    }

This is the route to return the confirmation page before deleting:

Route::get('delete/{id}', array('as'=>'deleteView', 'uses'=>'CompanyController@deleteView'));

This is the route for actual deleting:

Route::delete('deletecompany/{id}', array('as'=>'deleteCompany', 'uses'=>'CompanyController@destroy'));

17 Dec
3 years ago

ken4ward started a new conversation Unable To Retrieve Value From Select Box But ID

I am surprised of what I'm retrieving from a select box. I want to get the value of a select box, instead of that it retrieves the id not the value. please point with the correction where I'm doing the wrong thing.

Controller to save a product

 public function store(ProductRequest $productRequest)
    {
       $product = new Product;

       if($productRequest->isMethod('post')){

       $product->user_id     = Auth::user()->id;
       $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 function in the company model that is used in passing the database values to the select box.

public static function ReturnComanyPerUser()
    {
        return static::where('user_id', '=', Auth::user()->id)->orderBy('companyname')->lists('companyname', 'id');
    }

This is the view:

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

    <p>{!! Form::select('companyname', $companyforproduct) !!} </p>
    <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
    <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

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

This is the code that binds the company records in the db to the select box:

public function create()
    {
        return view('product.create')->with('companyforproduct', Company::ReturnComanyPerUser());
    }
13 Dec
3 years ago

ken4ward left a reply on Unable To Login Using A Custom Login And Email Confirmation

Yes, just for testing. That'll be implemented. Thanks.

ken4ward left a reply on Unable To Login Using A Custom Login And Email Confirmation

It's saving into the users table. It's gone pass the confirmation, the only problem is the login. I think the confirmadtion code might be the problem, since the user token might have been lost while moving from email to the site again.

ken4ward started a new conversation Unable To Login Using A Custom Login And Email Confirmation

I'm confused on what could be the problem with this code. It has worked in a test environent but refused to work now. My implementation is for user reation which goes thus: Registration page (with a confirmation code sent to the email confirmation) -> Email ( for confirmation and click on the link to return the login page) -> Login page (for the user to login with his credentials). Everythng goes on smoothing until the login in which when I input the login username/email and password it sees it as not matching hixh I'm very sure it matches because I use copy and paste. Controller:

public function store(UserRequest $userRequest)
    {
        $confirmation_code = str_random(30);

        $users = new User;
        $users->firstname             = $userRequest->firstname;
        $users->lastname              = $userRequest->lastname;
        $users->email                 = $userRequest->email;
        $users->username              = $userRequest->username;
        $users->password              = $userRequest->password;
        $users->confirmation_code     = $confirmation_code;

        Mail::send('email.verify', ['users' => $users, 'confirmation_code' => $confirmation_code ], 

            function ($message) use ($users) {

            $message->from('members@schoolproject.com', 'School Project Member');
            $message->to($users->email, $users->firstname)->subject('Registration process Message!');
        });

        $users->save();
       // return redirect()->route('index');
        return redirect()->action('UserController@index')->with('message', 'You have done successfully');
    }


    public function confirm($confirmation_code)
    {
        if( ! $confirmation_code)
        {
            throw new InvalidConfirmationCodeException;
        }

        $users = User::whereConfirmationCode($confirmation_code)->first();

        if ( ! $users)
        {
            throw new InvalidConfirmationCodeException;
        }

        $users->confirmed = 1;
        $users->confirmation_code = null;
        $users->save();

        //Flash::message('You have successfully verified your account.');
        //return redirect()->route('users.index');
        //return view('userpages.login');
        return redirect()->action('DashboardController@login');
    }


    public function login(Request $request){

        if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
                return redirect()->route('details')->with('message', 'You have successfully logged in');
        } 

        elseif (Auth::attempt(['email'=> $request->username, 'password' => $request->password])) {
                return redirect()->route('details')->with('message', 'You have successfully logged in');
        } 

        else {
            return redirect('login')
            ->with('message', 'Your username/password combination is not correct')
            ->withInput();
        }
    }

Login form


    <h1>Login</h1>
        
        {!! Form::open(array('url' => 'login', 'method' => 'post')) !!}
        {!! Form::token() !!}

            {!! Form::label('username', 'Username') !!}<br />
            {!! Form::text('username', Input::old('username')) !!} <br />

            {!! Form::label('password', 'Password') !!}<br />
            {!! Form::password('password') !!} <br />

            {!! Form::submit('Login') !!}

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

Please your professional contribution is highly welcome.

08 Dec
3 years ago

ken4ward left a reply on Trying To Get Property Of Non-object When Using Eloquent Models

@section('content')
    <h1>
        {!! ucfirst($question->user->username) !!}
    </h1>
    <p> {!! e($question->questions) !!} </p>
@stopassola 

The area giving problem is the relationship between the models of questions and user, so the area is:

<h1>
    {!! ucfirst($question->user->username) !!}
</h1>

This area is working well:

<p> {!! e($question->questions) !!} </p>

ken4ward started a new conversation Trying To Get Property Of Non-object When Using Eloquent Models

I appreciate the support from this forum. I want to retrieve the username by using the relationship between users and question, because the tutorial I'm following is User/Question based. I have In my models relationship have been defined like this: In the Question Model

use App\User;

class Question extends Model
{
    
    public function user(){
        return $this->belongsTo('App\User');
    }

In the User Model:

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

In the QuestionController I have it defined thus:

 public function show($id = null)
    {
        $question = Question::find($id);
        
        return view('questions.view')
            ->with('title', 'Make it Snappy - Question')
            ->with('question', $question);
    }

... and in the view.blade.php I defined it thus:

@section('content')
    <h1>
        {!! ucfirst($question->user->username) !!}
    </h1>
    <p> {!! e($question->questions) !!} </p>
@stop

When I run the page it throws the error as the title describes:

ErrorException in d97e482321a7dfdc3ee708c22c0fb08e line 3:
Trying to get property of non-object (View: C:\Users\ken4ward\Documents\xampp\htdocs\rphlimitedweb\resources\views\questions\view.blade.php)

What exactly is wrong? Please your wise instructive advice would well appreciated.

07 Dec
3 years ago

ken4ward left a reply on Unable To View Users Record. Page Throws Exception

Never mind again, it was a simple syntax error I committed prefixing @ instead of $ before a variable. I appreciate your candid support.

ken4ward left a reply on Unable To View Users Record. Page Throws Exception

Thanks. Words can't well express how well I appreciate your professional contribution. I have made these changes which have led to positive results. One more question, please, I'm still having this error thrown when I try to access the view page it throws this error. What's wrong on the page? I'm definitely sure it's passed the routing stage which was the former problem.

FatalErrorException in d97e482321a7dfdc3ee708c22c0fb08e line 2:
syntax error, unexpected '->' (T_OBJECT_OPERATOR)

view.blade.php

@extends('layouts.default')

@section('content')
    <p> {!! e(@question->questions) !!} </p>
@stopassola 

ken4ward started a new conversation Unable To View Users Record. Page Throws Exception

I have been on this for over 2 days, and really unpalatable. My quest is simple, just to view a user record when clicked. I have made the records hyperlinks by using Html::linkRoute This is my route: ''' Route::get('question/', array('as'=>'question', 'uses'=>'QuestionController@show')); ''' This is the index.blade.php file: ''' @extends('layouts.default')

@section('content')

Ask a Question

@if(Auth::check())
    @if($errors->has())
        <p>The following errors have occured:</p>
        <ul id="form-errors">
            {!! $errors->first('ask
            ', '<li>:message</li>') !!}
        </ul>
    @endif

        {!! Form::open(array('url' => 'ask', 'method' => 'post')) !!}
        {!! Form::token() !!}

        <p>
            {!! Form::label('question', 'Question') !!}<br />
            {!! Form::text('question', Input::old('question')) !!} <br />

            {!! Form::submit('Ask a Question') !!}
        </p>
        {!! Form::close() !!}
        @else
        <p>Please login to ask a question.</p>
@endif
<div id="questions">
    
    <h2>Unsolved Questions</h2>

    @if(!count($questions) > 0)
        <p>No questions have been asked</p>

    @else
        <ul>
            @foreach($questions as $question)
                    <li>{!! Html::linkRoute('question', str_limit($question->questions, 35), $question->id) !!} by 

                    @if(count($users) > 0)
                        @foreach($users as $user)
                            @if($user->id === $question->userid)
                                {!! ucfirst($user->username) !!}
                            @endif
                        @endforeach
                    @endif
                </li>
            @endforeach
        </ul>

        {!! $questions->render() !!}    
    
    @endif
</div>

@stop '''

This is the controller file: ''' public function show($id = null) { $question = Question::find($id); return view('questions.view') ->with('title', 'Make it Snappy - Question') ->with('question', $question) ->with('users', User::all()); } ''' This is the view page I'm routing to: ''' @extends('layouts.default')

@section('content')

{{ $question->questions }}

@stop '''

I have the questions field in my database. What exactly am I to do. Please, your expert's advice would be highly appreicated.