mehrdad70

mehrdad70

Member Since 1 Year Ago

Experience Points
1,830
Total
Experience

3,170 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
2
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.

Level 1
1,830 XP
Nov
28
2 days ago
Activity icon

Started a new Conversation Undefined Variable: Categories

i want send $categories variable to header.blade.php , but i get an error

FrontServiceProvider

class FrontServiceProvider extends ServiceProvider
{

    public function register()
    {

    }

    public function boot()
    {
        View::composer('front.layout.header' , function($view){
            $categories = (new Category())->tree();
             $view->with(compact('categories'));
        });
    }
}

Category Model

class Category extends Model
{
    protected $guarded = [];

    public function parentCategory()
    {
        return $this->belongsTo(Category::class , 'parent_id');
    }

    public function subCategory()
    {
        return $this->hasMany(Category::class , 'parent_id');
    }

    public function tree()
    {
        return $this->where('parent_id' , null)->with('subCategory')->get();
    }
}

Header.blade

     @foreach ($categories as $category)

     @endforeach                    	
Nov
27
3 days ago
Activity icon

Started a new Conversation Undefined Offset: 1

i wan to update coupon but i get an error When converting date jalali to Gregorian

    public function update(Coupon $coupon , Request $request)
    {
        list($day_start, $month_start, $year_start) = explode('/', $request->start_at);
        list($day_expired, $month_expired, $year_expired) = explode('/', $request->expired_at);
         $coupon->update([
            'title' => $request->title,
            'code' => $request->code,
            'amount' => $request->amount,
            'quantity' => $request->quantity,
            'is_general' => $request->is_general,
            'type' => $request->type,
            'description' => $request->description,
            'start_at' => implode("-", Verta::getGregorian($year_start,$month_start,$day_start)),
            'expired_at' => implode("-", Verta::getGregorian($year_expired,$month_expired,$day_expired)),
            ]);

        $coupon->categories()->sync($request->category_id);
        $coupon->users()->sync($request->user_id);
        $coupon->courses()->sync($request->course_id);

        return redirect(route('coupons.index'));
    }


Nov
25
5 days ago
Activity icon

Replied to SQLSTATE[22007]: Invalid Datetime Format: 1292 Incorrect Datetime Value

Is it a function to store Persian date as dateTime when stored in the database?

Activity icon

Replied to SQLSTATE[22007]: Invalid Datetime Format: 1292 Incorrect Datetime Value

It is not true?

            $table->timestamp('start_at');
            $table->timestamp('expired_at');
Activity icon

Replied to SQLSTATE[42S02]: Base Table Or View Not Found: 1146 Table

not work

class Coupon extends Model
{
    protected $guarded = [];

    protected $table = 'coupon_category';


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

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }
}
        Schema::create('coupon_category', function (Blueprint $table) {
            $table->unsignedBigInteger('coupon_id');
            $table->unsignedBigInteger('category_id');

            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('CASCADE');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('CASCADE');
        });
Activity icon

Started a new Conversation SQLSTATE[22007]: Invalid Datetime Format: 1292 Incorrect Datetime Value

I want to send the time in Persian and save it as a datetime in the database but i get an error

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1399-05-09 00:00:00' for column 'start_at' at row 1 (SQL: insert into `coupons` (`title`, `code`, `amount`, `quantity`, `is_general`, `type`, `description`, `start_at`, `expired_at`, `updated_at`, `created_at`) values (test1, 99808, 4, 1, 0, 0, ?, 1399-05-09 00:00:00, 1399-06-09 00:00:00, 2020-11-25 13:51:26, 2020-11-25 13:51:26))
    public function store(Request $request)
    {
        $coupon = Coupon::create([
            'title' => $request->title,
            'code' => $request->code,
            'amount' => $request->amount,
            'quantity' => $request->quantity,
            'is_general' => $request->is_general,
            'type' => $request->type,
            'description' => $request->description,
            'start_at' => date('Y-m-d H:i:s' , strtotime($request->start_at)),
            'expired_at' => date('Y-m-d H:i:s' , strtotime($request->expired_at)),
        ]);

        $coupon->categories()->sync($request->category_id);
        $coupon->users()->sync($request->user_id);
        $coupon->courses()->sync($request->course_id);

        return redirect(route('coupons.index'));

    }
Activity icon

Started a new Conversation SQLSTATE[42S02]: Base Table Or View Not Found: 1146 Table

how i can fix this error?

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'learning.category_coupon' doesn't exist (SQL: select * from `category_coupon` where `coupon_id` = 2)

    public function up()
    {
        Schema::create('coupons', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('code');
            $table->integer('amount');
            $table->boolean('is_general')->default(0);
            $table->unsignedInteger('quantity')->nullable();
            $table->enum('type'  , ['fixed' , 'percent']);
            $table->enum('status'  , ['enable' , 'disable'])->default('disable');
            $table->text('description')->nullable();
            $table->timestamp('start_at');
            $table->timestamp('expired_at');
            $table->timestamps();
        });

        Schema::create('coupons_user', function (Blueprint $table) {
            $table->unsignedBigInteger('coupon_id');
            $table->unsignedBigInteger('user_id');

            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('CASCADE');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
        });

        Schema::create('coupons_category', function (Blueprint $table) {
            $table->unsignedBigInteger('coupon_id');
            $table->unsignedBigInteger('category_id');

            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('CASCADE');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('CASCADE');
        });

        Schema::create('coupons_course', function (Blueprint $table) {
            $table->unsignedBigInteger('coupon_id');
            $table->unsignedBigInteger('course_id');

            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('CASCADE');
            $table->foreign('course_id')->references('id')->on('courses')->onDelete('CASCADE');
        });
    }
class Coupon extends Model
{
    protected $guarded = [];


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

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function courses()
    {
        return $this->belongsToMany(Course::class);
    }
}
Nov
24
6 days ago
Activity icon

Replied to Undefined Index Url Laravel

Do you think there is a solution?

Activity icon

Started a new Conversation Undefined Index Url Laravel

how i can fix this error in users module ?

ErrorException
Undefined index: name (View: C:\Users\sara\blogs\Modules\Milano\Dashboard\Resources\Views\layout\sidebar.blade.php)

Sidebar.php

<?php
return [
    'items' => [
        'dashboard' => [],
        'courses' => [],
        'products' => [],
        'categories' => [],
        'users' => [],
        'role-permissions' => [],
      
    ]
];

UserServiceProvider.php

<?php
namespace Milano\User\Providers;
use Illuminate\Support\ServiceProvider;
use Milano\User\Models\User;

class UserServiceProvider extends ServiceProvider
{
    public function register()
    {
        config()->set('auth.providers.users.model', User::class);
        $this->loadRoutesFrom(DIR. '/../Routes/user_routes.php');
        $this->loadMigrationsFrom(DIR . '/../Database/Migrations');
        $this->loadFactoriesFrom(DIR. '/../Database/Factories');
        $this->loadViewsFrom(DIR. '/../Resources/Views',  'User');
    }

    public function boot()
    {
        $this->app->booted(function(){
            config()->set('sidebar.items.users', [
                "icon" => "i-users",
                "title" => "کاربران",
                "url" => route('users.index'),
            ]);
        });
    }
}

user_routes.php

<?php

use Illuminate\Support\Facades\Route;

Route::group(['namespace' => 'Milano\User\Http\Controllers','middleware' => 'web'], function($router){
Route::mixin(new \Laravel\Ui\AuthRouteMethods());
Auth::routes(['verify' => true]);
   Route::get('logout' , 'Auth\[email protected]')->name('logout');
});

Route::group(['namespace' => 'Milano\User\Http\Controllers','middleware' => ['web', 'auth' , 'verified']], function ($router) {
    Route::resource('users', "UserController");
});

sidebar.blade.php

    <ul>


        @foreach(config('sidebar.items') as $item)
            <li class="item-li {{$item['icon']}} @if(str_starts_with(request()->url() , $item['url']))is-active @endif">
                <a href="{{$item['url']}}">{{$item['name']}}</a></li>
        @endforeach

    </ul>
Nov
10
2 weeks ago
Activity icon

Replied to UpdateOrCreate In Laravel 7

Thank you

Activity icon

Replied to UpdateOrCreate In Laravel 7

    Route::post('settings', '[email protected]')->name('settings.store');
    Route::post('settings/{setting}/update', '[email protected]')->name('settings.upadte');

    public function setSetting(Request $request)
    {
         if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }
        Setting::create(
            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

        );
        return back();
    }

    public function updateSetting(Request $request , Setting $setting)
    {

        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }

        $setting->update([
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $setting->logo,
                'symbol' =>  $symbolPath ?? $setting->symbol,
        ])  ;  
    }
}

I only have this one view and I want to create and edit this view

@extends('admin.dashboard.master')

@section('content')
<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="card">
            <div class="card-body">
                <div id="wizard1" role="application" class="wizard clearfix">
                <div class="content clearfix">
                    <h4  class="text-danger" style="text-align: center" id="wizard1-h-0" tabindex="-1" class="title current">تنظیمات سایت</h4>
                    <section id="wizard1-p-0" role="tabpanel" aria-labelledby="wizard1-h-0" class="body current" aria-hidden="false">
                        <form action="{{route('settings.store' ,  $setting->id )}}" method="post" enctype="multipart/form-data">
                            @csrf
                             <div class="control-group form-group">
                                <label class="form-label">عنوان سایت </label>
                                <input type="text" name="title" autocomplete="title" class="form-control required" placeholder="عنوان سایت را وارد کنید" value="{{$setting->first()->title  ?? ''}}">
                            </div>

                            <div class="control-group form-group">
                                <label for="">راه های ارتباطی</label>
                                <div class="row">

                                  <div class="col-6">
                                    <input type="text" name="phone" class="form-control text-left" placeholder="شماره تماس" value="{{$setting->first()->phone ?? ''}}">
                                  </div>

                                  <div class="col-6">
                                    <input type="text" name="email" class="form-control text-left" placeholder="ایمیل" value="{{$setting->first()->email ?? ''}}">
                                  </div>
                                </div>
                            </div>

                            <div class="control-group form-group">
                                <label for="">شبکه های اجتماعی</label>
                                <div class="row">

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">تلگرام</label>
                                    <input type="text" name="telegram" class="form-control text-left" placeholder="لینک تلگرام" value="{{$setting->first()->telegram ?? ''}}">
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">اینستاگرام</label>
                                    <input type="text" name="instagram" class="form-control text-left" placeholder="لینک اینستاگرام" value="{{$setting->first()->instagram ?? ''}}" >
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">توئیتر</label>
                                    <input type="text" name="twitter" class="form-control text-left" placeholder="لینک توئیتر" value="{{$setting->first()->twitter ?? ''}}" >
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">فیسبوگ</label>
                                    <input type="text" name="facebock" class="form-control text-left" placeholder="لینک فیسبوک" value="{{$setting->first()->facebock ?? ''}}">
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">یوتیوب</label>
                                    <input type="text" name="yoytube" class="form-control text-left" placeholder="لینک یوتیوب" value="{{$setting->first()->youtube ?? ''}}" >
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">لینکدین</label>
                                    <input type="text" name="linkedin" class="form-control text-left" placeholder="لینکدین" value="{{$setting->first()->linkedin ?? ''}}" >
                                  </div>

                                </div>
                            </div>

                            <div class="control-group form-group">
                                <div class="row">

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">لوگوی سایت</label>
                                    <input type="file" name="logo" class="form-control text-left" placeholder="لوگوی سایت">
                                    <br>
                                    <span>
                                      <img src="{{asset('/storage/' . $setting->first()->logo) }}" alt=""  width="70">
                                    </span>
                                  </div>

                                  <div class="col-6"  style="margin-top: 20px">
                                    <label for="">نمادک سایت</label>
                                    <input type="file" name="symbol" class="form-control text-left" placeholder="نمادک سایت">
                                    <br>
                                    <span>
                                      <img src="{{asset('/storage/' . $setting->first()->symbol)}}" alt="" width="70">
                                    </span>
                                  </div>
                                </div>
                            </div>

                            <div class="control-group form-group">
                                <label class="form-label">توضیحات سایت </label>
                                <textarea name="description" class="form-control required" placeholder="توضیحات مختصری درباره وبسایت" id="" cols="30" rows="5">{{$setting->first()->description ?? ''}}</textarea>
                            </div>

                            <br>
                            <div class="control-group form-group mt-10">
                                <button type="submit" class="btn btn-outline-info waves-effect">ثبت اطلاعات وبسایت</button>
                            </div>
                        </form>
                    </section>
                </div>
            </div>
            </div>
        </div>
    </div>
</div>
@endsection
Activity icon

Replied to UpdateOrCreate In Laravel 7

yes only one setting record exists in setting table, but i want update this record

Activity icon

Replied to UpdateOrCreate In Laravel 7

I did all the things you mentioned and I do not have a unique field in the settings section and I want all the fields to be created once and then updated each time

    public function setSetting(Request $request , Setting $setting)
    {
         if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }
        Setting::updateOrCreate(
            [
                'email' => $request->email,
            ],

            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $setting->logo,
                'symbol' =>  $symbolPath ?? $setting->symbol,
            ],

        );
        return back();
    }
Nov
09
3 weeks ago
Activity icon

Replied to UpdateOrCreate In Laravel 7

The new record is stored in the database, but I want to save a record and that record is updated

Activity icon

Replied to UpdateOrCreate In Laravel 7

App\Setting {#1463 ▼
  #guarded: []
  #connection: "mysql"
  #table: "settings"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:15 [▼
    "id" => 1
    "title" => "فروشگاه اینترنتی2"
    "description" => "لتالتلتلتالتالتالتالتالتلتالتال"
    "logo" => null
    "symbol" => null
    "phone" => "9187391441"
    "email" => "[email protected]"
    "telegram" => "http://instagram.com/mehrdad"
    "instagram" => "http://instagram.com/mehrdad"
    "twitter" => "http://instagram.com/mehrdad"
    "youtube" => null
    "facebock" => "http://instagram.com/mehrdad"
    "linkedin" => "http://instagram.com/mehrdad"
    "created_at" => "2020-11-09 14:21:14"
    "updated_at" => "2020-11-09 14:38:19"
  ]
  #original: array:15 [▼
    "id" => 1
    "title" => "فروشگاه اینترنتی2"
    "description" => "لتالتلتلتالتالتالتالتالتلتالتال"
    "logo" => null
    "symbol" => null
    "phone" => "9187391441"
    "email" => "[email protected]"
    "telegram" => "http://instagram.com/mehrdad"
    "instagram" => "http://instagram.com/mehrdad"
    "twitter" => "http://instagram.com/mehrdad"
    "youtube" => null
    "facebock" => "http://instagram.com/mehrdad"
    "linkedin" => "http://instagram.com/mehrdad"
    "created_at" => "2020-11-09 14:21:14"
    "updated_at" => "2020-11-09 14:38:19"
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}
Activity icon

Replied to UpdateOrCreate In Laravel 7

The new record is stored in the database, but I want to save a record and that record is updated

    public function store(Request $request)
    {
        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }
        Setting::updateOrCreate(
            [
                'phone' => $request->phone,
                'email' => $request->email,
            ],

            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

        );
        return back();
    }
Activity icon

Replied to UpdateOrCreate In Laravel 7

Do not all fields need to be updated?

Activity icon

Replied to UpdateOrCreate In Laravel 7

Do you have an idea to solve this challenge?

Activity icon

Started a new Conversation UpdateOrCreate In Laravel 7

hello , i want to updateOrCreate Setting . this code only create but update is not work

    public function store(Request $request , Setting $setting)
    {
        dd($setting);
        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }
        Setting::updateOrCreate(
            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

        );
        return back();
    }
Nov
08
3 weeks ago
Activity icon

Started a new Conversation In_array() Expects Parameter 2 To Be Array, Null Given

I want the selected categories to be selected for editing coupons

        Schema::create('category_coupon', function (Blueprint $table) {

            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('coupon_id');

            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('CASCADE');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('CASCADE');

            $table->primary(['coupon_id', 'category_id']);
        });
    public function edit(Coupon $coupon)
    {
        $categories = Category::all();
        $users = User::all();
        $products = Product::all();
        return view('admin.coupons.edit' , compact('products' , 'users' , 'categories' , 'coupon'));
    }

class Coupon extends Model
{
    protected $guarded = [];

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
 
}
                                <div class="col-6"  style="margin-top: 20px">
                                    <label class="form-label">تخفیف دسته بندی</label>
                                    <select name="category_id[]" id=""  data-live-search="true" class="form-control " multiple   title="تخفیف دسته بندی" >
                                        @foreach ($coupon->categories as $category)
                                            {{ in_array($category->id , $coupon->category_id)->toArray() ? 'selected' : '' }}                                         
                                        @endforeach     
                                    </select>                                  
                                </div>
Activity icon

Started a new Conversation Delete Tags In Polymorphic Many To Many

how i can delete tags in polymorphic many to many from table tags and taggable after delete Article

this code only delete tags form table tags but not work from table taggable

public function destroy(Article $article)
{

    if ($article->tags) {
        foreach ($article->tags as $tag) {
            $tag->delete();
        }
    }

    $article->delete();
    return AjaxResponse::success();
}
Nov
07
3 weeks ago
Activity icon

Started a new Conversation How To Change The Color Of Select2 Tags?

how i can to change the color tag in select2

Nov
06
3 weeks ago
Activity icon

Started a new Conversation Create Tag For Products An Articles With Polymorphic Relationship

I proceeded this way but I did not get results and I receive various errors Articles are created but tags are not

tabe_tags

    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('tag_name');
            $table->timestamps();
        });

        Schema::create('taggables', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tag_id');
            
            $table->unsignedBigInteger('taggable_id');
            $table->unsignedBigInteger('taggable_type');

            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('CASCADE');
            $table->timestamps();
        });
    }

model Tag

class Tag extends Model
{
    protected $fillable = ['tag_name' , 'tag_id' , 'taggable_id' , 'taggable_type'];
    
    public function articles()
    {
        return $this->morphedByMany(Article::class , 'taggable');
    }
    public function products()
    {
        return $this->morphedByMany(Product::class , 'taggable');
    }
}

model Article

    public function tags()
    {
        return $this->morphToMany(Tag::class , 'taggable');    
    }

create form article

@extends('admin.dashboard.master')

@section('content')
<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="card">
            <div class="card-body">
                <div id="wizard1" role="application" class="wizard clearfix">
                <div class="content clearfix">
                    <h5 id="wizard1-h-0" tabindex="-1" class="title current text-center text-danger">ایجاد مقاله</h5>
                    <br>
                    <section id="wizard1-p-0" role="tabpanel" aria-labelledby="wizard1-h-0" class="body current" aria-hidden="false">
                        <form action="{{route('articles.store')}}" method="post" enctype="multipart/form-data">
                            @csrf
 

                            <div class="control-group form-group">
                                <div class="row">

                                <div class="col-6">
                                        <label class="form-label">عنوان مقاله </label>
                                    <input type="text" name="title" class="form-control required" placeholder="عنوان مقاله" value="{{old('title')}}">
                                </div>
                                
                                <div class="col-6">
                                    <label class="form-label">عنوان انگلیسی مقاله </label>
                                    <input type="text" name="slug" class="form-control required" placeholder="عنوان انگلیسی مقاله" value="{{old('slug')}}">
                                </div>

                                <br>

                                <div class="col-6" style="height: auto">
                                    <label class="form-label"> برچسپ ها </label>
 
                                    <input name="tag_name[]" style="height: auto" id="tagSelect" multiple  class="form-control" value="{{old('tag_ids')}}" >
                                </div>

    
                                <div class="col-6">
                                    <label class="form-label"> دسته بندی </label>
                                    <select name="categories[]"  data-live-search="true" id="categories" title="انتخاب دسته بندی مرتبط" class="form-control selectpicker" multiple>
                                        @foreach ($categories as $category)
                                            <option value="{{$category->id}}">{{$category->name}}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <br>

                                <div class="col-6">
                                    <label class="form-label">بنر مقاله </label>
                                    <div class="custom-file">
                                        <input class="custom-file-input" name="image"  id="customFile" type="file"> 
                                        <label class="custom-file-label" for="customFile">اپلود  بنر مقاله</label>
                                    </div>
                                </div>
                            </div>

                            </div>
                                
                            <div class="control-group form-group">
                                <label class="form-label">توضیحات مقاله </label>
                                <textarea name="body" class="form-control required" id="my-editor" cols="30" rows="5"></textarea>
                            </div>


                            <br>
                            <div class="control-group form-group mt-10">
                                <button type="submit" class="btn btn-outline-info waves-effect">درج مقاله</button>
                                <a href="{{route('articles.index')}}" class="btn btn-outline-danger waves-effect">انصراف</a>
                            </div>
                        </form>
                    </section>
                </div>
            </div>
            </div>
        </div>
    </div>
</div>
@endsection

Article controller

    public function store(ArticleRequest $request , ArticleRepository $articleRepository)
    {
        $this->authorize('create' , Article::class);
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image');
            $imageName = $imagePath->getClientOriginalName();
            $dir = 'articles';
            $path = $imagePath->storeAs($dir, $imageName, 'public');
        }



        $article = Article::create([
            'title' => $request->title,
            'slug' => $request->slug,
            'body' => $request->body,
            'user_id' => auth()->id(),
            'image' => $path
        ]);

                
        $article->categories()->sync($request->categories);

        $article->comments()->create([
            'body' => $request->body,
            'user_id' => auth()->id(),
            'parent_id' => $request->parent_id
        ]);

        
        $article->tags()->create([
            'tag_name' => $request->tag_name,
            'taggable_id' => $article->id,
            'taggable_type' => get_class($article),
        ]);

        
        return redirect(route('articles.index'));
    }
Nov
05
3 weeks ago
Activity icon

Started a new Conversation Polymorphic Relationship Many To Many In Laravel 7

How can I store tags using polymorphic relationships for products and articles?

    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
        
        Schema::create('taggables', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tag_id');
            
            $table->unsignedBigInteger('taggable_id');
            $table->unsignedBigInteger('taggable_type');

            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('CASCADE');
            $table->timestamps();
        });
    }
class Tag extends Model
{
    protected $fillable = ['name' , 'tag_id' , 'taggable_id' , 'taggable_type'];
    
    public function articles()
    {
        return $this->morphedByMany(Article::class , 'taggable');
    }
    public function products()
    {
        return $this->morphedByMany(Product::class , 'taggable');
    }
}
    public function store(ArticleRequest $request , ArticleRepository $articleRepository)
    {
        $this->authorize('create' , Article::class);
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image');
            $imageName = $imagePath->getClientOriginalName();
            $dir = 'articles';
            $path = $imagePath->storeAs($dir, $imageName, 'public');
        }


        $article = Article::create([
            'title' => $request->title,
            'slug' => $request->slug,
            'body' => $request->body,
            'user_id' => auth()->id(),
            'image' => $path
        ]);

                
        $article->categories()->sync($request->categories);

        $article->comments()->create([
            'body' => $request->body,
            'user_id' => auth()->id(),
            'parent_id' => $request->parent_id
        ]);

        
        $article->tags()->create([
            'name' => $request->tags,
            'taggable_id' => $article->id,
            'taggable_type' => get_class($article)
        ]);

        return redirect(route('articles.index'));
    }
                            <div class="control-group form-group">
                                <label class="form-label"> برچسپ ها </label>
                                <input name="tags" class="form-control select2 js-example-tokenizer"  >
                            </div>
Nov
02
4 weeks ago
Activity icon

Replied to Update Record If Exists Or Create New Record Laravel

I want the record to be created if it does not exist, otherwise the record will be updated

Activity icon

Replied to Update Record If Exists Or Create New Record Laravel

it did not work. A new record is created and the update is not done

Activity icon

Replied to Update Record If Exists Or Create New Record Laravel

Is created. But the update is not done

    public function store(Request $request)
    {
        if ($request->hasFile('logo')) {
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir, $filName, 'public');
        }

        if ($request->hasFile('symbol')) {
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir, $filName, 'public');
        }
        Setting::updateOrCreate(
            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

            [
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ],

        );
        return back();
    }
Nov
01
4 weeks ago
Activity icon

Replied to Update Record If Exists Or Create New Record Laravel

it did not work. This code only creates a new record

public function store(Request $request , Setting $setting)
    {
        if($request->hasFile('logo')){
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir , $filName , 'public');
        }

        if($request->hasFile('symbol')){
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir , $filName , 'public');
        }

        $setting = Setting::updateOrCreate([
            'title' => $request->title,
            'phone' => $request->phone,
            'email' => $request->email,
            'description' => $request->description,
            'telegram' => $request->telegram,
            'instagram' => $request->instagram,
            'twitter' => $request->twitter,
            'facebock' => $request->facebock,
            'youtube' => $request->youtube,
            'linkedin' => $request->linkedin,
            'logo' => $logoPath ?? $setting->logo,
            'symbol' =>  $symbolPath ?? $setting->symbol,
        ]);

        return back();
    }
Activity icon

Started a new Conversation Update Record If Exists Or Create New Record Laravel

I want the record to be updated if it exists and to be created if it does not exist , but this code is not work

        Schema::create('settings', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->longText('description');
            $table->string('logo');
            $table->string('symbol');
            $table->integer('phone');
            $table->string('email');
            $table->string('website')->nullable();
            $table->string('telegram')->nullable();
            $table->string('instagram')->nullable();
            $table->string('twitter')->nullable();
            $table->string('youtube')->nullable();
            $table->string('facebock')->nullable();
            $table->string('linkedin')->nullable();
            $table->timestamps();
        });
    Route::resource('settings', 'SettingController');

public function store(Request $request , Setting $setting)
    {
        if($request->hasFile('logo')){
            $logo = $request->file('logo');
            $filName = $logo->getClientOriginalName();
            $dir = 'logo';
            $logoPath = $logo->storeAs($dir , $filName , 'public');
        }

        if($request->hasFile('symbol')){
            $symbol = $request->file('symbol');
            $filName = $symbol->getClientOriginalName();
            $dir = 'symbol';
            $symbolPath = $symbol->storeAs($dir , $filName , 'public');
        }

        if(Setting::latest()->first()){
            Setting::create([
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ]);
        }else{
            Setting::latest()->first()->update([
                'title' => $request->title,
                'phone' => $request->phone,
                'email' => $request->email,
                'description' => $request->description,
                'telegram' => $request->telegram,
                'instagram' => $request->instagram,
                'twitter' => $request->twitter,
                'facebock' => $request->facebock,
                'youtube' => $request->youtube,
                'linkedin' => $request->linkedin,
                'logo' => $logoPath ?? $request->logo,
                'symbol' =>  $symbolPath ?? $request->symbol,
            ]);
        }

        return back();
    }
Oct
30
1 month ago
Activity icon

Replied to Too Few Arguments To Function App\Http\Controllers\Admin\CommentController::accept(), 1 Passed And Exactly 2 Expected

class Comment extends Model
{
    protected $fillable = ['body' , 'status' , 'parent_id' , 'user_id' , 'commentable_type' , 'commentable_type'];


    const STATUS_ACCEPT = 'accept';
    const STATUS_REJECT = 'reject';
    const STATUS_PENDING = 'pending';

    static $updateStatus  = [self::STATUS_ACCEPT , self::STATUS_REJECT , self::STATUS_PENDING];

    public function commentable()
    {
        return $this->morphTo();
    }

    public function child()
    {
        return $this->hasMany(Comment::class , 'parent_id');    
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
    public function accept(Comment $comment , Request $request)
    {
        if($comment->updateStatus($comment , 'accept')){
            Comment::where('id' , $comment)->update([Comment::STATUS_ACCEPT , $request->status]);  
            return AjaxResponse::success();
        }
    }
Activity icon

Replied to Too Few Arguments To Function App\Http\Controllers\Admin\CommentController::accept(), 1 Passed And Exactly 2 Expected

   function updateStatus(event , route , message , status , field = 'status'){
        if (confirm(message)) {
        $.post(route , { _method: "patch" , _token: "{{ csrf_token() }}"})

        .done(function (response) {  
            $(event.target).closest('tr').find('td.'+ field).text(status);

        })


        .fail(function (response) {  

        })
    }

    }
                                <a href="" onclick="event.preventDefault(); updateStatus(event , '{{route('comments.accept' , $comment->id)}}' , 'آیا از تایید این آیتم اطمینان دارید؟' , 'تایید شد' , 'status')" class="btn btn-sm btn-outline-primary waves-effect" data-toggle="tooltip" data-placement="bottom"  data-original-title="تایید دیدگاه"><i class="fa fa-check"></i> </a>

Activity icon

Replied to Too Few Arguments To Function App\Http\Controllers\Admin\CommentController::accept(), 1 Passed And Exactly 2 Expected

exception: "BadMethodCallException"
file: "C:\Users\Mehrdad\Desktop\store\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php"
line: 50
message: "Call to undefined method App\Comment::updateStatus()"
Activity icon

Replied to Too Few Arguments To Function App\Http\Controllers\Admin\CommentController::accept(), 1 Passed And Exactly 2 Expected

No, I did not send , Do you think there is a solution to this error?

Activity icon

Started a new Conversation Too Few Arguments To Function App\Http\Controllers\Admin\CommentController::accept(), 1 Passed And Exactly 2 Expected

hello , I get an error when confirming comments

exception: "ArgumentCountError"
file: "C:\Users\Mehrdad\Desktop\store\app\Http\Controllers\Admin\CommentController.php"
line: 34
message: "Too few arguments to function App\Http\Controllers\Admin\CommentController::accept(), 1 passed and exactly 2 expected"
trace: [{function: "accept", class: "App\Http\Controllers\Admin\CommentController", type: "->"}, {,…}, {,…},…]
                                    <a href="" onclick="event.preventDefault(); updateStatus(event , '{{route('comments.accept' , $comment->id)}}' , 'آیا از تایید این آیتم اطمینان دارید؟' , 'تایید شد' , 'status')" class="btn btn-sm btn-outline-primary waves-effect" data-toggle="tooltip" data-placement="bottom"  data-original-title="تایید دیدگاه"><i class="fa fa-check"></i> </a>

    Route::patch('comment/{comment}/accept' , '[email protected]')->name('comments.accept');

    public function accept(Comment $comment , $status)
    {
        if($comment->updateStatus( $comment , 'accept')){
            Comment::where('id' , $comment)->update(['status' , $status]);  
            return AjaxResponse::success();
        }
    }
Oct
23
1 month ago
Activity icon

Started a new Conversation SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column 'title' In 'field List'

What is the cause of this error?

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('seller_id')->unsigned();
            $table->bigInteger('category_id')->unsigned()->nullable();
            $table->string('image')->nullable();
            $table->string('title');
            $table->string('slug');
            $table->float('priority')->nullable();
            $table->string('price',10);
            $table->string('percent', 5);
            $table->enum('type', \Milano\Product\Models\Product::$types);
            $table->enum('status',\Milano\Product\Models\Product::$statuses);
            $table->enum('confirmation_status',\Milano\Product\Models\Product::$confirmationStatuses);
            $table->longText('body')->nullable();
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('SET NULL');
            $table->foreign('seller_id')->references('id')->on('users')->onDelete('CASCADE');

        });
        Schema::create('image_products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->string('src');
            $table->integer('main_image');
            $table->timestamps();

            $table->foreign('product_id')->references('id')->on('products')->onDelete('CASCADE');

        });
public function store(Request $request)
    {

        $images = [];
        if($request->hasFile('images')){
            foreach ($request->images as $image){
               $images[] = $image->store("photos/product/" , 'public');
            }
        }

        $product = Product::create([
            'seller_id' => $request->seller_id,
            'category_id' => $request->category_id,
            'title' => $request->title,
            'slug' => Str::slug($request->slug),
            'priority' => $request->priority,
            'price' => $request->price,
            'percent' => $request->percent,
            'type' => $request->type,
            'status' => $request->status,
            'body' => $request->body,
            'image' => $images[0] ?? null
        ]);
        foreach ($images  as $key => $image){
            $product  = $image->create([
               'src' => $image,
               'main_image' => $key = 0
            ]);
        }

        return back();
    }
class Product extends Model
{
    /**
     * @var mixed
     */

    protected $guarded = [];
    protected $table = 'users';


    const TYPE_CASH = 'cash';
    const TYPE_CHECK = 'check';
    static $types = [self::TYPE_CHECK, self::TYPE_CASH];

    const CONFIRMATION_STATUS_ACCEPTED = 'accepted';
    const CONFIRMATION_STATUS_REJECTED = 'rejected';
    const CONFIRMATION_STATUS_PENDING = 'pending';
    static $confirmationStatuses = [self::CONFIRMATION_STATUS_ACCEPTED, self::CONFIRMATION_STATUS_PENDING, self::CONFIRMATION_STATUS_REJECTED];

    const STATUS_AVAILABLE = 'available';
    const STATUS_UNAVAILABLE = 'unavailable';
    static $statuses = [self::STATUS_AVAILABLE, self::STATUS_UNAVAILABLE];
    

    public function seller()
    {
        return $this->belongsTo(User::class, 'seller_id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class , 'category_id');
    }

    public function images()
    {
        return $this->hasMany(ImageProduct::class , 'product_id');
    }
}
<form action="{{ route('products.store') }}" class="padding-30" method="post" enctype="multipart/form-data">
                @csrf
                <x-input name="title" placeholder="عنوان محصول" type="text" required/>
                <x-input type="text" name="slug" placeholder="نام انگلیسی محصول" class="text-left" required />


                <div class="d-flex multi-text">
                    <x-input type="text" class="text-left mlg-15" name="priority" placeholder="ردیف محصول" />
                    <x-input type="text" placeholder="مبلغ محصول" name="price" class="text-left" required />
                    <x-input type="number" placeholder="درصد فروشنده" name="percent" class="text-left" required />
                </div>
                <x-select name="seller_id"  >
                    <option value="">انتخاب فروشنده محصول</option>
                    @foreach($sellers as $seller)
                        <option value="{{ $seller->id }}" @if($seller->id == old('seller_id')) selected @endif>{{ $seller->name }}</option>
                    @endforeach
                </x-select>


                <x-tag-select name="tags"/>

                <x-select name="type" required>
                    <option value="">نوع محصول</option>
                    @foreach(\Milano\Product\Models\Product::$types as $type)
                        <option value="{{ $type }}"
                                @if($type == old('type')) selected @endif
                        >@lang($type)</option>
                    @endforeach
                </x-select>

                <x-select name="status" required>
                    <option value="">وضعیت محصول</option>
                    @foreach(\Milano\Product\Models\Product::$statuses as $status)
                        <option value="{{ $status }}"
                                @if($status == old('status')) selected @endif
                        >@lang($status)</option>
                    @endforeach
                </x-select>

                <x-select name="category_id" required>
                    <option value="">دسته بندی</option>
                    @foreach($categories  as $category)
                        <option value="{{ $category->id }}"
                                @if($category->id == old('category_id')) selected @endif
                        >{{ $category->title }}</option>
                    @endforeach
                </x-select>

                <input type="file" name="images[]" multiple placeholder="عکس محصول">
                <x-textarea placeholder="توضیحات محصول" name="body" />
                <br>
                <button class="btn btn-webamooz_net">ایجاد محصول</button>
            </form>
Oct
22
1 month ago
Activity icon

Started a new Conversation Trying To Get Property 'avatar' Of Non-object

how i can fix this error ?

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('fname');
            $table->string('lname');
            $table->string('mobile')->nullable();
            $table->enum('gender' , User::$genders)->nullable();
            $table->string('avatar')->nullable();
            $table->text('address')->nullable();
            $table->text('post_code')->nullable();
            $table->longText('description')->nullable();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');
            $table->timestamps();
        });
    }
class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use HasRoles;


    public function profile()
    {
        return $this->hasOne(Profile::class);    
    }
    
}
class Profile extends Model
{
    protected $guarded = [];

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

}
    Route::get('profile' , '[email protected]')->name('users.profile');
    Route::post('profile' , '[email protected]')->name('users.profile');

    public function profile()
    {
        return view('admin.users.profile');    
    }

    public function profileStore(Request $request)
    {        
        if ($request->hasFile('avatar')) {
            $imagePath = $request->file('avatar');
            $imageName = $imagePath->getClientOriginalName();
            $dir = 'users';
            $path = $imagePath->storeAs($dir, $imageName, 'public');
            if(auth()->user()->profile->avatar){
                Storage::delete('public\'. auth()->user()->profile->avatar);
            }    
        }


        
        if(auth()->user()->profile){
            auth()->user()->profile()->update([
                'fname' => $request->fname,
                'lname' => $request->lname,
                'mobile' => $request->mobile,
                'gender' => $request->gender,
                'address' => $request->address,
                'post_code' => $request->post_code,
                'description' => $request->description,
                'avatar' => $path ??  auth()->user()->profile->avatar,
            ]);
          }else{
            auth()->user()->profile()->create([
                'fname' => $request->fname,
                'lname' => $request->lname,
                'mobile' => $request->mobile,
                'gender' => $request->gender,
                'address' => $request->address,
                'post_code' => $request->post_code,
                'description' => $request->description,
                'avatar' => $path ,
                'user_id' => auth()->id(),
            ]);
          }            
        return back();
    }
                    <img src="{{asset('/storage/' . auth()->user()->profile->avatar)}}"   class="rounded-circle mCS_img_loaded">

Oct
17
1 month ago
Activity icon

Started a new Conversation Update Is_main_image In Laravel 7

hello , how i can update is_main_image in edit product

        Schema::create('image_products', function (Blueprint $table) {
            $table->unsignedBigInteger('product_id');
            $table->string('src');
            $table->integer('is_main_image');
            $table->timestamps();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('CASCADE');
        });
    public function product()
    {
        return $this->belongsTo(Product::class , 'id');    
    }

    public function images()
    {
        return $this->hasMany(ImageProduct::class, 'product_id');
    }
    public function update($id , Request $request )
    {
        $product = Product::findOrFail($id);
        $now = Carbon::now();
        $images = [];
        if ($request->hasFile('images')) {            
            foreach ($request->images as $image) {
                $images[] = $image->store("photos/Product/$now->year/$now->month/$now->day", 'public');
            }
            if($product->images){
                foreach ($product->images as  $image) {
                    Storage::delete('public\' . $image->src);
                }
                $product->images()->delete();
            }
        }
        
        $product->update([
            'title' => $request->title,
            'slug' => $request->slug,
            'stock' => $request->stock,
            'price' => $request->price,
            'sku' => $request->sku,
            'description' => $request->description,
            'body' => $request->body,
            'category_id' => $request->category_id,
            'brand_id' => $request->brand_id,
            'user_id' => auth()->id(),
            'image' => $images[0] ?? $product->image
        ]);      
          
        foreach ($images as $key => $image) {
            $product->images()->create([
                'src' => $image,
                'is_main_image' => $key == 0
            ]);
        }

        return redirect(route('products.index')); 
    }
                            <div class="control-group form-group">
                                <div class="row">
                                    <div class="col-lg-12 d-flex">
                                        @foreach ($images as $image)
                                        <div class="col-sm-2">
                                            <img src="{{'/storage/' . $image->src}}" alt="" width="150">
                                            <input type="radio" name="is_main_image" id="" value="{{$image}}" 
                                            @if($image->is_main_image == 1) checked @endif
                                            >
                                        </div>
                                         @endforeach
                                    </div>
                                </div>
                            </div>
Oct
14
1 month ago
Activity icon

Replied to Route [users.index] Not Defined. Laravel

First I commented on all the paths and then I executed the command php artisan optimize:clear and removed the paths from the comment again and I got an error.

Activity icon

Started a new Conversation Route [users.index] Not Defined. Laravel

please help me for fixied this error

Route::namespace('Admin')->middleware(['web' , 'auth'])->group(function(){
    Route::get('dashboard' , '[email protected]')->name('dashboard.index');
    Route::get('profile' , '[email protected]')->name('users.profile');
    Route::resource('users', 'UserController');
    Route::resource('categories', 'CategoryController');
    Route::resource('products', 'ProductController');
    Route::resource('roles', 'RoleController');
    Route::resource('permissions', 'PermissionController');
    Route::resource('articles', 'ArticleController');
    Route::resource('brands', 'BrandController');
    Route::resource('attributeGroups', 'AttributeGroupController');
    Route::resource('attributes', 'AttributeController');
    Route::resource('attributeItems', 'AttributeItemController');
    Route::resource('coupons', 'CouponController');
    Route::post('attributes/{GroupId}' , '[email protected]')->name('attributes.store');
    Route::post('attributeItems/{AttributeId}' , '[email protected]')->name('attributeItems.store');
    Route::get('category/{category}' , '[email protected]')->name('category.attribute');
    Route::post('category/{category}' , '[email protected]')->name('category.storeAttribute');
});
class DashboardServicePovider extends ServiceProvider
{
    public function register()
    {
        
        config()->set('sidebar.items.dashboard' , [
            "name" => "پیش خوان",
            "icon" => "fa-store-alt",
            "url" => url('dashboard'),
        ]);
    
        config()->set('sidebar.items.users' , [
            "name" => "کاربران",
            "icon" => "fa-users",
            "url" => route('users.index'),
        ]);  
    
        config()->set('sidebar.items.categories' , [
            "name" => "دسته بندی ها",
            "icon" => "fa-database",
            "url" => route('categories.index'),
        ]) ;  
        config()->set('sidebar.items.products' , [
            "name" => "محصولات",
            "icon" => "fa-bullhorn",
            "url" => route('products.index'),
        ]) ;  
        config()->set('sidebar.items.roles' , [
            "name" => "سطح دسترسی کاربر",
            "icon" => "fa-user-shield",
            "url" => route('roles.index'),
        ]) ;  
        config()->set('sidebar.items.articles' , [
            "name" => "مقالات",
            "icon" => "fa-file-signature",
            "url" => route('articles.index'),
        ]) ;  
        config()->set('sidebar.items.brands' , [
            "name" => "برند ها",
            "icon" => "fa-certificate",
            "url" => route('brands.index'),
        ]) ;  
        config()->set('sidebar.items.attributes' , [
            "name" => "ویژگی های محصول",
            "icon" => "fa-receipt",
            "url" => route('attributeGroups.index'),
        ]) ;  
    
        config()->set('sidebar.items.coupons' , [
            "name" => "کد تخفیف",
            "icon" => "fa-gift",
            "url" => route('coupons.index'),
        ]) ;  
    }

    public function boot()
    {
    }
}
Oct
10
1 month ago
Activity icon

Started a new Conversation Update Image In Laravel 7

How can we update the photo? In such a way that the previous photo is completely deleted and the new photo is saved...

The Store method works

    public function store(BrandRequest $request , BrandRepository $brandRepository)
    {
        if ($request->file('image')) {
            $imagePath = $request->file('image');
            $imageName = $imagePath->getClientOriginalName();
            $dir = 'brands';
            $path = $imagePath->storeAs($dir, $imageName, 'public');
        }

        $brandRepository->store($request , $imageName);
        return redirect(route('brands.index'));
    }

The Store method not works , I want the photo to be updated both in the database and in the storage folder after the update

    public function update($id , BrandRequest $request , BrandRepository $brandRepository)
    {
        $brand = $brandRepository->findOrFail($id);
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image');
            $imageName = $imagePath->getClientOriginalName();
            $path = $imagePath->storeAs($imageName, 'public');
            Storage::delete(['public\'. $brand->image]);

        }

        $brand->update([
            'name' => $request->name,
            'slug' => $request->slug,
            'body' => $request->body,
            'image' => $path,
            'user_id' => auth()->id(),
        ]);
        $brand->categories()->sync($request->categories);

        return redirect(route('brands.index'));
    }
        Schema::create('brands', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('name');
            $table->string('slug');
            $table->string('image')->nullable();
            $table->longText('body')->nullable();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');

        });
Activity icon

Started a new Conversation Property [name] Does Not Exist On This Collection Instance.

Hello . how i can fix this error

class Category extends Model
{
    protected $guarded = [];

    public function brands()
    {
        return $this->belongsToMany(Brand::class);    
    }
}
class Brand extends Model
{
    protected $guarded = [];

    public function categories()
    {
        return $this->belongsToMany(Category::class);    
    }
}
    
<td>{{$brand->categories->name}}</td>


brand_id	category_id
7			1
Oct
08
1 month ago
Activity icon

Started a new Conversation Perfect Structure For Coupon Table Laravel

Is this structure correct?

    public function up()
    {
        Schema::create('coupons', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('code')->unique();
            $table->float('discount_amount');
            $table->integer('quantity')->nullable();
            $table->tinyInteger('used')->nullable();
            $table->enum('type' , ['percent'  , 'fixed']);
            $table->enum('status' , ['enable'  , 'disable']);
            $table->timestamp('start_at')->nullable();
            $table->timestamp('expire_at')->nullable();
            $table->timestamps();
        });

        Schema::create('coupon_user', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('coupon_id')->nullable();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('SET NULL');
            $table->foreign('coupon_id')->references('id')->on('coupons')->onDelete('SET NULL');
        });
    }

Oct
07
1 month ago
Activity icon

Started a new Conversation Invalid Argument Supplied For Foreach() Laravel

how i can fix this error ?

        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('category_id')->nullable();
            $table->unsignedBigInteger('brand_id')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->string('title');
            $table->string('slug');
            $table->string('images')->nullable();
            $table->string('price');
            $table->integer('stock');
            $table->string('sku')->nullable();
            $table->string('description')->nullable();
            $table->longText('body')->nullable();
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories')->onDelete('SET NULL');
            $table->foreign('brand_id')->references('id')->on('brands')->onDelete('SET NULL');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE');

        });
        Schema::create('image_products', function (Blueprint $table) {
            $table->unsignedBigInteger('product_id');
            $table->string('src');
            $table->integer('is_main_image');
            $table->timestamps();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('CASCADE');
        });

class ImageProduct extends Model
{
    protected $guarded = [];

    public function product()
    {
        return $this->belongsTo(Product::class , 'id');    
    }
}
class Product extends Model
{
    protected $guarded = [];

    public function images()
    {
        return $this->hasMany(ImageProduct::class, 'product_id');
    }

    public static function booted()
    {
        static::deleting(function (Product $product) {
            foreach ($product->images as  $image) {
                Storage::delete('public\' . $image->src);
            }
            $product->images()->delete();
        });
    }
}

    public function destroy($id)
    {
        $product = Product::findOrFail($id);
        $product->delete();
        return back();
    }

Sep
30
2 months ago
Activity icon

Started a new Conversation What Structure Do You Suggest For Implementing The Attribute And Values Database Of Products?

Is this a logical structure?

Note: I have not implemented the products section yet

    public function up()
    {
        Schema::create('attributes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('order')->nullable();
            $table->timestamps();
        });
        Schema::create('values', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('attribute_id');
            $table->string('values');
            $table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('CASCADE');
            $table->timestamps();
        });
   
    }
Sep
26
2 months ago
Activity icon

Replied to Remove Image Laravel 7

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: delete from article_images where id is null).

<?php

namespace App\Observers;

use App\ArticleImage;
use Illuminate\Support\Facades\Storage;

class ArticleImageObserver
{
    public function deleting(ArticleImage $image)
    {
        if(Storage::disk('public')->exists($image->src)){
            Storage::disk('public')->delete($image->src);
        }
    }
}

<?php

namespace App\Observers;

use App\Article;

class ArticleObserver
{
    public function deleting(Article $article)
    {
        $article->images->each->delete();
    }
}


    public function destroy($id)
    {
        $article = Article::findOrFail($id)->delete();
        return back();
    }


    public function boot()
    {
        Article::observe(ArticleObserver::class);
        ArticleImage::observe(ArticleImageObserver::class);
    }