cosmic_learning

Member Since 6 Years Ago

Experience Points
77,190
Total
Experience

2,810 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
989
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 16
77,190 XP
Nov
24
1 month ago
Activity icon

Started a new Conversation Unable To Save To One-to-one Relation

I have One To One relationship between the models: ApiRequest and ApiResponse.

This is part of my ApiRequest model :


    public function apiResponse()
    {
        return $this->hasOne('App\ApiResponse', 'request_id');
    }

   public function storeApiResponse(array $apiResponseData)
    {
        $this->apiResponse()->create(apiResponseData);
    }

When I try to store data to ApiResponse from my controller in this way, it works fine:

	$this->apiRequestModel->apiResponse()->create($data);

However, when I try to do that through the method in the model, it doesn't work

	 $this->apiRequestModel->storeApiResponse($data);

I'm getting: Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$create

Any idea why?

Nov
23
1 month ago
Activity icon

Replied to Best Approach For Testing HTTP Requests

Agreed for Unit test. But about an Integration test (where I still don't want to hit the APIs)?

Activity icon

Started a new Conversation Best Approach For Testing HTTP Requests

Let's say I have a Client class that uses the Laravel HTTP Client:

class BestBuyClient
{
    public function checkAvailability($stockId): StockStatus
    {
        ////hard-coded url to simplify the example
        $url = "https://api.ebay.com/commerce/catalog/v1_beta/product?sku={$stockId}"; 
        $results = HTTP::get($url)->json();

        return new StockStatus(
            $results['onlineAvailability'] ?? '',
            $results['salePrice'] ?? ''
        );
    }
}

Then, let's say I have a service class that uses that client class:

class TrackStockService
{
    protected $bestBuyClient;

    public function __construct(BestBuyClient $bestBuyClient)
    {
        $this->bestBuyClient = $bestBuyClient;
    }

    protected function refreshStock()
    {
        $availability = $this->bestBuyClient->checkAvailability(1); //hard-coded Id to simplify the example
        //do additional operations with the returned response
    }

}

What would be the best approach to test the Service class in Integration test? I'm thinking of two solutions:

  1. Fake the HTTP requests using the Laravel feature
  2. Mock the bestBuyClient in the service and return a fake object with dummy data

Which one of these is a better approach and why?

Activity icon

Replied to How To Mock A Job Object In Laravel?

The Facades by their design are resolved from the container. That's why I'm expecting the shouldReceive approach to work https://laravel.com/docs/8.x/mocking#mocking-facades

If I let the exception handler to catch it, then it will break the controller execution. I need the controller to continue with its execution (with the rest of the code) even if the job can't be pushed to the queue. That's why I need to catch it in the controller.

Nov
22
1 month ago
Activity icon

Replied to How To Mock A Job Object In Laravel?

I agree with your point. However, the issue I have is that I can't find a way how to cover with a test the code in the catch block in the controller.

Since it's in the controller, that can be tested only with a feature test. I need to mock this line: App\Jobs\ProcessRunEndpoint::dispatch($apiRequest)->onQueue('run'); and return a faker that will throw an exception which will cause execution on the code in the catch block and then it will be tested. Do you have an idea how to do that, or do you maybe have a different idea on how to test the code in the catch block in the provided example?

Activity icon

Replied to How To Mock A Job Object In Laravel?

Right, that's what I'm trying to achieve in the example above.

Activity icon

Started a new Conversation How To Mock A Job Object In Laravel?

When it comes to Queue testing in Laravel, I use the provided Queue Fake functionality. However, there is a case where I need to create a Mock for a Job class.

I have the following code that pushes a job to a Redis powered queue:

      $apiRequest->storeRequestedData($requestedData); // a db model
      // try-catch block in case the Redis server is down
        try {
            App\Jobs\ProcessRunEndpoint::dispatch($apiRequest)->onQueue('run');
            $apiRequest->markJobQueued();
        } catch (\Exception $e) {
            //handle the case when the job is not pushed to the queue
        }

I need to be able to test the code in the catch block. Because of that, I'm trying to mock the Job object in order to be able to create a faker that will throw an exception.

I tried this in my Unit test:

       ProcessRunEndpoint::shouldReceive('dispatch');

That code returns: Error: Call to undefined method App\Jobs\ProcessRunEndpoint::shouldReceive(). I also tried to swap the job instance with a mock object using $this->instance() but it didn't work as well.

That said, how can I test the code in the catch block?

Nov
18
1 month ago
Activity icon

Awarded Best Reply on Array To String Conversion Laravel Blade

fit it by

replece

is_null with empty

@if(is_null($posts))

to

@if (!empty($posts) )
Activity icon

Replied to Array To String Conversion Laravel Blade

fit it by

replece

is_null with empty

@if(is_null($posts))

to

@if (!empty($posts) )
Activity icon

Replied to Array To String Conversion Laravel Blade

fix it but still same error on update

Activity icon

Replied to Array To String Conversion Laravel Blade

miss spell but the same error pups up

{!!old("title", $lang->pivot->title ??null)!!}
Nov
17
2 months ago
Activity icon

Started a new Conversation Array To String Conversion Laravel Blade

use same foor for create and update on create all is ok but on update trow. array to string conversion laravel blade

my code

controller

public function edit(Post $posts)
    {
        $tag = Tag::all();
        $languages = Language::all();
        $categories = Category::all();
        return view('admin.posts.edit', compact('posts', 'categories', 'tag', 'languages'));
    }

    /**
     * @param Update $request
     * @param Post $post
     * @return RedirectResponse
     */
    public function update(Update $request, Post $post): RedirectResponse
    {
        if ($request->hasFile('featured_image',)) {
            $post->update(
                $request->except('featured_image', 'title', 'description') + [
                    'featured_image' => $this->verifyAndStoreImage($request),
                ]
            );
        } else {
            $post->update($request->except('title', 'description'));
        }
        $sync_data = [];
        for ($i = 0, $iMax = count($request['title']); $i < $iMax; $i++) {
            $sync_data[$request['title'][$i]] = [
                'title' => $request['title'][$i],
                'description' => $request['description'][$i],
                'language_id' => $request['language_id'][$i],
            ];
        }
        $post->language()->sync($sync_data, true);
        $post->tags()->sync($request->tags, true);
        $post->categories()->sync($request->category, true);

        Session::flash('error_msg', trans('messages.post_not_found'));
        return redirect()->to(route('posts.edit', $post));
    }

and blade if


@if(is_null($posts))
    {!! Form::model($posts, [
    'route' => ['posts.update', $posts->id],
    'method' => 'PUT',
    'class' => 'form-horizontal',
    'files'=> true])
    !!}
@else
    {!! Form::open([
    'route' => 'posts.store',
    'class' => 'form-horizontal',
    'files'=> true])
    !!}
@endif
@include('admin.layouts.notify')
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header card-header-tabs card-header-primary">
                <div class="nav-tabs-navigation">
                    <div class="nav-tabs-wrapper">
                        <span class="nav-tabs-title">Lang:</span>
                        <ul class="nav nav-tabs" data-tabs="tabs">
                            @foreach($languages as $key => $language)
                                <li class="nav-item">
                                    <a class="nav-link {{ $key === 0 ? 'active' : '' }}" href="#{{$language->name}}"
                                       data-toggle="tab">
                                        <i class="material-icons">cloud</i>{{$language->name}}
                                        <div class="ripple-container"></div>
                                    </a>
                                </li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    @foreach($languages as $key => $language)
                        <div class="tab-pane {{ $key === 0 ? 'active' : '' }}" id="{{$language->name}}">
                            <table class="table">
                                <tbody>
                                <div class="form-group">
                                    <input type="text" class="form-control" placeholder="title"
                                           name="title[]{{$language->id}}"
                                           value="@foreach($posts->language as $lang) @if($lang->pivot->language_id == $language->id) {!!old("title", $lang->pivot->title ?? null)!!} @endif @endforeach">
                                </div>
                                <textarea class="ckeditor" id="{{$language->name}}"
                                          name="description[]{{$language->id}}">@foreach($posts->language as $lang)
                                        @if($lang->pivot->language_id == $language->id) {{old("description", $lang->pivot->description ?? null)}} @endif @endforeach
                                </textarea>
                                </tbody>
                            </table>
                        </div>
                        <input type="hidden" class="form-control"
                               placeholder="language_id"
                               name="language_id[]{{$language->id}}" value="{{$language->id}}">
                    @endforeach
                </div>
            </div>
        </div>
    </div>
    <div class="form-group col-4">
        <label for="tags" class="col-sm-3 control-label">{{trans('messages.category')}}</label>
        <div class="form-group">
            <select class="form-control js-example-basic-multiple" id="category" name="category[]" multiple="multiple">
                @foreach ($categories as $category)
                    <option value="{{ $category->id }}">@for ($i = 0; $i < $category->depth; $i++)
                            - @endfor {{ $category->title }}</option>
                @endforeach
            </select>
        </div>
        <h4 class="title"></h4>
        <div class="fileinput text-center fileinput-new col-12" data-provides="fileinput">
            <div class="fileinput-new thumbnail img-circle">
                <img src="@if(empty($posts->featured_image)){{ asset('images/image_placeholder.jpg')}}@else {{ old('featured_image', $posts->imageUrl ?? null) }}@endif"
                     alt="image">
            </div>
            <div class="fileinput-preview fileinput-exists thumbnail img-circle" style=""></div>
            <div>
                <span class="btn btn-round btn-rose btn-file">
                    <span class="fileinput-new">Add Photo</span>
                    <span class="fileinput-exists">Change</span>
                    <input type="hidden" value="" name="featured_image"><input type="file"
                                                                               name="featured_image">
                    <div class="ripple-container"></div></span>
                <br>
                <a href="#pablo" class="btn btn-danger btn-round fileinput-exists" data-dismiss="fileinput">
                    <i class="fa fa-times"></i> Remove
                    <div class="ripple-container">
                        <div class="ripple-decorator ripple-on ripple-out"
                             style="left: 62px; top: 25.6719px; background-color: rgb(255, 255, 255); transform: scale(15.5098);"></div>
                    </div>
                </a>
            </div>
        </div>
    </div>
    <div class="form-group col-8">
        <label for="rating_desc"
               class="col-sm-3 control-label">{{trans('messages.rating_desc')}}</label>
        <div>
                <textarea id="meta_description" class="form-control" name="meta_description"
                          placeholder="{{trans('messages.meta_description')}}">{{ old('meta_description', $posts->meta_description ?? null) }}</textarea>
        </div>
    </div>
    <div class="form-group col-4">
        <label for="tags" class="col-sm-3 control-label">{{trans('messages.select_tags')}}</label>
        <div class="form-group">
            <select class="form-control select2-multiple" id="tags" name="tags[]" multiple="multiple">
                @foreach($tag as $tags)
                    <option value='{{ $tags->id }}'>{!! $tags->title !!} </option>
                @endforeach
            </select>
        </div>
    </div>
    <div class="form-group col-8">
        <label for="status" class="control-label">{{trans('messages.status')}}</label>
        <div>
            <select id="status" class="form-control" name="status">
                <option value="{{config('constants.STATUS_PUBLISHED')}}">{{trans('messages.published')}}</option>
                <option value="{{config('constants.STATUS_HIDDEN')}}">{{trans('messages.hidden')}}</option>
            </select>
        </div>
    </div>
</div>{{--row--}}
<div class="form-actions">
    <div class="row">
        <div class="col-md-offset-3 col-md-9">
            {{ Form::submit(trans('messages.save'), ['name' => 'submit', 'class'=>'btn purple' ]) }}
        </div>
    </div>
</div>
<input type="hidden" name="author_id" value="{{ Auth::user()->id  }}">
{!! Form::close() !!}
@section('scripts')
    <script src="//cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
    <script>
        var options = {
            filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images',
            filebrowserImageUploadUrl: '/laravel-filemanager/upload?type=Images&_token=',
            filebrowserBrowseUrl: '/laravel-filemanager?type=Files',
            filebrowserUploadUrl: '/laravel-filemanager/upload?type=Files&_token='
        };
    </script>
    <script>
        CKEDITOR.replace('editor', options);
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.js-example-basic-multiple').select2();
        });
    </script>
    <!-- select2 -->
    <script type="text/javascript">
        $('#tags').select2().val({!! json_encode($posts->tags()->allRelatedIds()) !!}).trigger('change');
        $('#category').select2().val({!! json_encode($posts->categories()->allRelatedIds()) !!}).trigger('change');
    </script>
@endsection
@section('style')
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>
@endsection

trows the error before I hit the update method in controller

Nov
12
2 months ago
Activity icon

Replied to Function Name Must Be A String

Yes my constructor

<?php

namespace App\Http\Controllers;

use App;
use App\Models\Category;
use App\Models\Language;
use App\Models\Newsletter;
use App\Models\Product;
use App\Models\Settings;
use App\Models\Theme;
use DB;
use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use URL;
use View;

class Controller extends BaseController
{

    use AuthorizesRequests,
        DispatchesJobs,
        ValidatesRequests;

    public $path;

    /**
     * Controller constructor.
     */
    public function __construct()
    {
        try {
            $theme = Theme::where('activated', '=', 1)->first();
            $path = $theme->view_path;
        } catch (Exception $e) {
            $path = 'travel';
        }
        $popular = Product::where('workflow_id', '=', '1')->orderBy('views', 'desc')->limit(4)->get();
        $newsletter = Newsletter::all();

        $language = Language::all();
        $this->path = $path;
        View::share([
            'path' => $path,
            'popular' => $popular,
            'newsletter' => $newsletter,
            'language' => $language
        ]);
    }

    /**
     * @return mixed
     */
    public function feed()
    {
        $feed = App::make("feed");
        $feed->setCache(60, 'laravelFeedKey');
        if (!$feed->isCached()) {
            $posts = DB::table('product')->orderBy('created_at', 'desc')->take(20)->get();
            $feed->title = 'Your title';
            $feed->description = 'Your description';
            $feed->logo = 'http://yoursite.tld/logo.jpg';
            $feed->link = url('feed');
            $feed->setDateFormat('datetime'); // 'datetime', 'timestamp' or 'carbon'
            $feed->pubdate = $posts[0]->created_at;
            $feed->lang = 'en';
            $feed->setShortening(true); // true or false
            $feed->setTextLimit(100); // maximum length of description text
            $author = 'Admin';
            foreach ($posts as $post) {
                $feed->add($post->title, $author, URL::to($post->slug), $post->updated_at, $post->description);
            }
        }
        return $feed->render('rss');
    }

    public function sitemap()
    {
        $sitemap = App::make("sitemap");
        $posts = DB::table('product')->orderBy('created_at', 'desc')->get();
        foreach ($posts as $post) {
            $sitemap->add($post->slug, $post->title, $post->updated_at);
        }
        $sitemap->store('xml', 'sitemap');
    }

}
Activity icon

Replied to Function Name Must Be A String

[22:25:04] LOG.error: Function name must be a string {"userId":1,"exception":{}}

Screenshot-2020-11-12-at-23-29-33

Nov
10
2 months ago
Activity icon

Replied to Function Name Must Be A String

this is my code in view to be honest I dont understand you qestion :)

   @foreach($popular as $populars)
        <div class="tag">
            <a href="/post/{{$populars->slug}}">{!! $populars->title!!}</a>
        </div>
        @endforeach
Activity icon

Replied to Function Name Must Be A String

I list the $popular in foreach in blade to show the post

Activity icon

Replied to Function Name Must Be A String

find the problem

 $popular = Post::orderBy('views', 'desc')->where(
            'status',
            config('constants.STATUS_PUBLISHED')
        )->take(5)->get();

need to be

 $popular = Post::orderBy('views', 'desc')->where(
            'status',
            config('constants.STATUS_PUBLISHED')
        )->take(5);
Activity icon

Replied to Function Name Must Be A String

public function __construct()
    {
        try {
            $theme = Theme::where('activated', '=', 1)->firstOrFail();
            $path = $theme->view_path;
        } catch (Exception $e) {
            $path = 'travel';
        }
        $this->path = $path;
        $settings = Setting::firstOrFail();
        $country = Country::get();
        $tree = Category::getList();
        $tag = Tag::get();
        $popular = Post::orderBy('views', 'desc')->where(
            'status',
            config('constants.STATUS_PUBLISHED')
        )->take(5)->get();
        $ads = Ad::all();
        $popular_tags = Tag::join('post_tag', 'post_tag.tag_id', '=', 'tags.id')
            ->groupBy('tags.id')
            ->get(['tags.id', 'tags.title', DB::raw('count(tags.id) as tag_count')])
            ->sortByDesc('tag_count')
            ->take(20);

        View::share([
            'path' => $path,
            'tree' => $tree,
            'last_post' => $last_post,
            'ads' => $ads,
            'tag' => $tag,
            'popular' => $popular,
            'country' => $country,
            'settings' => $settings,
            'popular_tags' => $popular_tags
        ]);
    }
Activity icon

Started a new Conversation Function Name Must Be A String

After update to laravel 8 this error shows everyvere every route

Oct
31
2 months ago
Activity icon

Commented on Fake It Till You Make It

Is it fine that we don't write a separate test for ClientFactory? Instead, we cover it through Stock.

Oct
30
2 months ago
Activity icon

Commented on Initial Relationships

What would be the pros and cons if we used the Eloquent pivot functionality to handle the Stock relationship?

Oct
27
2 months ago
Activity icon

Replied to Seed Large Seeder. 1M Row

it works :)

Activity icon

Started a new Conversation Seed Large Seeder. 1M Row

Have table seeder with over 1mlion row, see it trows

'max_allowed_packet' bytes laravel seed
Aug
21
4 months ago
Activity icon

Replied to Passing String From Controller To View

You are write my method is

 public function validateRooms(Store $request): string
    {

        $booking_exists = Booking::whereRoomTypeId($request['room_type_id'])
            ->where('status', 1)
            ->whereBetween('start_date', [$request['start_date'], $request['end_date']])
            ->orWhereBetween('end_date', [$request['end_date'], $request['start_date']])
            ->orWhere(static function ($query) use ($request) {
                $query->where('start_date', '<=', $request['start_date'])
                    ->where('end_date', '>=', $request['end_date']);
            })->count();
        $quantity = RoomType::whereId($request['room_type_id'])->select('quantity')->first()->quantity;
        if ($booking_exists >= $quantity) {
            $request->session()->flash('message', 'This date is already booked');
            return redirect()->back();
        }
        $start_date = Carbon::parse($request['start_date']);
        $end_date = Carbon::parse($request['end_date']);
        $days = $start_date->diffInDays($end_date);
        $price = RoomType::join('prices', 'room_types.price_id', '=',
            'prices.id')
            ->where('room_types.id', $request['room_type_id'])
            ->select('price')->first()->price;
        if (empty($days)) {
            $amount = 1 * $price;

        } else {
            $amount = $days * $price;
        }

        return view('stripe', compact('amount'));
Activity icon

Replied to Passing String From Controller To View

i sory little bit nerviest

            $amount = $days * $price;

now just whant to echo it in a view

example you need to pay {{ $amount}}

Activity icon

Replied to Passing String From Controller To View

i try this scenarios

Activity icon

Replied to Passing String From Controller To View

try

        return view('room')->with('amount', $amount);

        return view('room')->with($amount);

        return view('room', $amount);

        return view('room', compact('amount'));
Activity icon

Replied to Passing String From Controller To View

        $start_date = Carbon::parse($request['start_date']);
        $end_date = Carbon::parse($request['end_date']);
        $days = $start_date->diffInDays($end_date);

end I what to pass $days to a view to print it

Activity icon

Started a new Conversation Passing String From Controller To View

Hi all have calculation that i need to past to a view ,the result is a string, positive number and I whant to pass to a view end echo it {{ $day}} tray with compact or with helper but getting

Return value of App\Http\Controllers\Controller::countRooms() must be of the type string, object returned