morteza

morteza

Member Since 1 Year Ago

Experience Points 53,620
Experience Level 11

1,380 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 487
Lessons
Completed
Best Reply Awards 8
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

02 Jan
7 months ago

morteza left a reply on Vue Laravel Localization

What i do is to use view composer to load translations and send to layout, set translations as a javascript variable, add a function to javascript to translate using that variable. In view composer:

        $lang_files = File::files(resource_path() . '/lang/' . app()->getLocale());
        $trans = collect();
        foreach ($lang_files as $f) {
            $filename = pathinfo($f)['filename'];
            $trans->$filename = trans($filename);
        }

In layout blade file:

<script>
        window.trans = {!! $trans->toJson()  !!}
    </script>

In app.js file:

function __(key, params = false) {
    let trans = _.get(window.trans, key, key);

    if (trans.substring(trans.length - 1) !== " ") {
        trans = trans + ' ';
    }

    if (params) {
        _.forEach(params, (param, index) => {
            if (trans.indexOf(':' + index + ' ') > 0) {
                trans = _.replace(trans, ':' + index, param);
            }
        });
    }

    if (trans.substring(trans.length - 1) !== " ") {
        trans = trans.substring(0, trans.length - 1);
    }

    return trans;
}

Vue.prototype.__ = (key, params = false) => {
    return __(key, params);
};

11 Oct
10 months ago

morteza left a reply on How To Unit Test Eloquent Scopes?

Thank you @D9705996 . I see you are telling me it should be on integration test not in unit test, am i right? I want to see if there is a way to unit test my repository function. I just want to know if eloquent calls the scope.

morteza started a new conversation How To Unit Test Eloquent Scopes?

I want to unit test to see if specific scope will be called if i call repository method but i don't know how can i do this. Let say i have a Mobile model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mobile extends Model
{
    protected $casts = [
        'verified_at' => 'datetime',
    ];

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

    public function scopeNumberIs($query, $number)
    {
        return $query->where('number', $number);
    }
}

And i have a MobileRepository for it:

namespace App\Repositories;

use App\Contracts\MobileInterface;
use App\Contracts\UserInterface;
use App\Mobile;
use App\User;

class MobileRepository extends Repository implements MobileInterface
{
    public function __construct(Mobile $mobileModel)
    {
        parent::__construct($mobileModel);
    }

    public function getRelatedUserByNumber(string $number): UserInterface
    {
        $user = optional($this->model->numberIs($number)->first())->user;

        if (is_null($user)) {
            $user = new User;
        }

        return new UserRepository($user);
    }
}

Now i want to make a test to see is scopeNumberIs will be fired when i call getRelatedUserByNumber. I mocked Mobile model but it's calling some other methods that i don't know how to handle them! should i mock them too or there is an easier way. How you do this?

28 Feb
1 year ago

morteza left a reply on How To Get All Route List?

Thanks @patriknemecek for your reply, but i want route list as array or json.

morteza started a new conversation How To Get All Route List?

I want to pass all laravel routes to vue using array or json. How can i get laravel routes as array or json?

27 Feb
1 year ago
18 Jan
1 year ago

morteza left a reply on Pattern Suggestion For Requests

You can create one CRUDRequest class and in each controller instead of injecting Request class inject your CRUDRequest class:

class UserController
{
    public function create(CRUDRequest $request)
    {
        // CRUDRequest will be call and will do all validation automatically
        // You just need to call your target function on it
        $request->persist();
    }

    public function update(CRUDRequest $request, User $user)
    {
        $request->persistExists($user);
    }

        public function delete(CRUDRequest $request, User $user)
    {
        $request->remove($user);
    }
}

morteza left a reply on Create A User Register On Admin Side

This is laravel register user method:

public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
                        ?: redirect($this->redirectPath());
    }

1- validate inputs, 2- create a user and fire event 3- login as registered user 4- return to previous visited url. You can modify this function to what you want. I think step 1 and 2 is all you want. Just validate inputs and create user then fire Registered event.

morteza left a reply on How To Use Event "Illuminate\Mail\Events\MessageSending" To Replace $to According To Environment

You can use getEnv('APP_ENV') to check your environment, but it seems it's best use case for mailtrap

morteza left a reply on Attached Forms

If all your data is related and should insert in the same time, you can do in 2 ways: 1- using wizard forms, user see form 1 and can click on next to see form 2 and form 2 has previous and next button, as well as form 3. All next and previous buttons handle with jquery and don't submit form except finish button on last form. 2- using vue in very easy and fun way.

morteza left a reply on Always The Same Error In The Debug - RecursiveDirectoryIterator::hasChildren()

I think it's about directory permissions, try

sudo chmod 777 -R storage

morteza left a reply on Laravel - How To Calculate The Sum Of Objects In An Array In Blade View

@tykus because i need it in view and i don't want to add extra code to controller. But main reason is that it is simple. Let say you want to use vue instead of blade for this page, why should i prepare $total in controller while vue can make it easily in client side! This is what i think. Maybe you right.

morteza left a reply on Output Model JSON Id For String

add this line to your model:

protected $incrementing = false;

morteza left a reply on Laravel - How To Calculate The Sum Of Objects In An Array In Blade View

You can add extra @php in your foreach:

@foreach($transaction->options as $option)
    @php
        $total = isset($total) ? $total + $option->pivot->price : 0;
    @endphp
                  <div class="row">
                    <div class="col-md-6">
                      <p>Option description: {{ $option->description }}</p>
                      <p>Price: {{ $option->pivot->price }}</p>
                      @php($total += $option->pivot->price)
                    </div>
                  </div>
                  <hr>
                @endforeach
                <div class="row">
                  <div class="col-md-6">
                    <h4>Options total: {{ $total }}</h4>
                  </div>
                </div>

Or the better solution is to use collection sum:

<h4>Options total: {{ $transaction->options->sum(function ($option) {
    return $option->pivot->price;
) }}</h4>

morteza left a reply on Test Against Value In Array/JSON

You can use this:

ScrapeObject::first()->->where('data->caption', 'Your Caption')
                ->get();

Also read this: laravel-json-where

morteza left a reply on Not Selected Categories In Edit View

Try this: In model:

// Remove this function
public function getKategoriaAttribute()
{
    return $this->categories->pluck('id')->all();
}

in [email protected]:

public function edit($id)
    {
        $categories = Category::all('name', 'id');
        $artykul = Article::with('categories')->findOrFail($id);
        return view('panel_admina.edytuj_aktualnosc', compact('artykul', 'categories'));
    }

In view:

<select multiple class="form-control" id="kategoria" name="Kategoria[]">
@foreach($categories as $category)
<option value="{{ $category->id }}" @if ($artykul->categories->contains($category)) selected="selected" @endif>{{ $category->name }}</option>
@endforeach
</select>

morteza left a reply on Mystery Error In View

Check to see if all $office->company->name are exists.

17 Jan
1 year ago

morteza left a reply on List With A Selected Item

@foreach ($companies as $company)
    <option value="{{ $company->id}}" selected="{{ $company->id == old('company_id',$company->id) ? 'selected' : '' }}">
                          {{ $company->company_name }}
    </option>
@endforeach

morteza left a reply on Can't Post Comments After Completing Laravel 5.4 Episode 19

If you are adding comment using create method, check comment model to have $fillables with user_id field or set up guard.

morteza left a reply on Dynamic Appends/hidden/visible On Model Relations.

So i suggest you to use query builder with joins, then you have complete control over everything.

16 Jan
1 year ago

morteza left a reply on Need Clarification On Query Strings With Laravel

You can do this:

Route::post('/post/{post}/comments', '[email protected]');

And in store method on controller:

public function store(Post $post)
{
  // You have now access to $post model
}

morteza left a reply on Path To Storage Folder

It seems you didn't use $location on saving file?!

morteza left a reply on Help Figuring Out The Proper Relationship

class Invite extends Model
{
    /**
     * Get all of the owning invitable models.
     */
    public function invitable()
    {
        return $this->morphTo();
    }
}

class Storyteller extends Model
{
    /**
     * Get all of the owning storytellerable models.
     */
    public function storytellerable()
    {
        return $this->morphTo();
    }
}

class Exercise extends Model
{
    /**
     * Get all of the exercise's invites.
     */
    public function invites()
    {
        return $this->morphMany('App\Invite', 'invitable');
    }

    /**
     * Get all of the exercise's storytellers.
     */
    public function storytellers()
    {
        return $this->morphMany('App\Storyteller', 'storytellerable');
    }
}


morteza left a reply on More Variables GET (paginate And Sorting)

if $search_results is a pagination object you can do this:

{{ $search_results->appends(['sort' => request('sort')])->links() }}

morteza left a reply on File Storage With Job Dispatching

As documents says: Binary data, such as raw image contents, should be passed through the base64_encode function before being passed to a queued job. Otherwise, the job may not properly serialize to JSON when being placed on the queue.

So try passing file address instead of file.

morteza left a reply on How To Access To $ChargeResponse->email ...

uncomment this line:

//$ChargeResponse = json_encode($ChargeResponse);

then change json_encode with json_decode

morteza left a reply on Flipping Model->Relationship Order

You can add an accessor in your invites model and add it to class appends array:

protected $appends = ['player'];

public function getPlayerAttribute()
{
    return $this->player;
}

morteza left a reply on Path To Storage Folder

Did you run php artisan storage:link ?

morteza left a reply on Redirect To The Previous Page After Registration And Login

Laravel already does it for you.

morteza left a reply on How To Do Login Authentication With Many To Many Relationship Table Field.

Add use hash to LoginController:

use Illuminate\Support\Facades\Hash;

Overwrite login method in your LoginController:

public function login(Request $request)
    {
        $this->validate([
        'email' => 'required|string',
        'password' => 'required|string',
                'group_id' => 'nullable|integer',    
        ]);

       
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
    if ($request->group_id) {
        $group = Group::find($request->group_id);
        $user = $group->users()->where('email', $request->email)->first();
                if ($user && Hash::check($request->password, $hashedPassword)) {
            return $this->sendLoginResponse($request);  
        }
    } else if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);  
        }
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

morteza left a reply on How To Do Login Authentication With Users Table->email And Groups Table->id In Many To Many Relationship

Add use hash to LoginController:

use Illuminate\Support\Facades\Hash;

Overwrite login method in your LoginController:

public function login(Request $request)
    {
        $this->validate([
        'email' => 'required|string',
        'password' => 'required|string',
                'group_id' => 'nullable|integer',    
        ]);

       
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
    if ($request->group_id) {
        $group = Group::find($request->group_id);
        $user = $group->users()->where('email', $request->email)->first();
                if ($user && Hash::check($request->password, $hashedPassword)) {
            return $this->sendLoginResponse($request);  
        }
    } else if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);  
        }
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

morteza left a reply on Laravel Multi File Validation Fails

Check if you added multipart enctype on your html form

morteza left a reply on Multiple Image Upload And Insert Into Multiple Row Of Database...

This should do what you want:

public function store(Request $request)
    {
        $files = $request->file('file');
        $filesCollection = collect([]);
     foreach ($files as $file) {
         $path = $request->photo->store('/images/products');
    $filesCollection->push($path);
    }

    $filesCollection->each(function ($path) {
             Media::create([
                         'path' => $path,
                     ]);
        });
     return redirect()->route('media.index');
 }

morteza left a reply on Where Clause In Inner Relationship

Try this:

$cities = City::whereHas('state', function ($query) use ($countiesId) {
    return $query->where('active', true)->orWhereHas('country', function ($query) use ($countiesId) {
    return $query->whereIn('id', $countiesId);
} );
})->get

morteza started a new conversation Using JSON Column Instead Of Typical Fields

As you know, mysql 5.7 provides json fields. What could be down sides of using a data json fields instead of having many nullable fields on a table? Let's say i'm working on a products table which has length, width, height, thickness, margin, ... all in nullable property. I think is better to use json data column instead of using all these nullable columns. But i don't know what could be down sides!