ethar

ethar

Member Since 11 Months Ago

Experience Points
15,090
Total
Experience

4,910 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
111
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 4
15,090 XP
Sep
27
1 month ago
Activity icon

Started a new Conversation Laravel 8 Route : (Cant Find Controller) No Such File Or Directory

i create new route file admin.php


Route::group(['prefix' => 'admin', 'middleware' => 'auth:admin', 'namespace' => 'Admin'], function () {
    Route::get('/dashboard', '[email protected]');
});

in route service provider i activate $namespace and add route file to middleware, and activate namespace


    protected $namespace = 'App\Http\Controllers';
    public function boot()
    {
        $ this->configureRateLimiting();
            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));
        });
    }

but when visit /admin/dashboard i got this error


include(/Library/WebServer/Documents/pos/vendor/composer/../../app/Http/Admin/DashboardController.php): failed to open stream: No such file or directory

Note: DashboardController.php inside app/Http/Controllers/Admin/DashboardController.php

Sep
24
1 month ago
Activity icon

Started a new Conversation Return Last Record By Forign_key

i have chapters table, student take exams ,

in student_exams i store ('id','chapter_id','mark','user_id')

I want to list all chapters and marks of last taken exam related to chapter.

i try this code


            $chapter = Chapter::select('id', 'title_ar')
                ->with(['studentExams' => function ($q) {
                    $q->select('chapter_id', 'mark')
                        ->where('student_id', Auth::user()->id)
                        ->orderby('id', 'DESC')
                        ->first();
                }])->get();

but it returns the last exam is taken, not the last exam in the selected chapter.

Sep
22
1 month ago
Activity icon

Started a new Conversation All Relations And Indexing Removed After Upload Database

after uploading the database to the server, all relations have been removed,

in localhost its exist, how to solve this problem, I cant run migrate:fresh because the site owner already has insert data to the database to I cant rerun migration.

any idea to solve this problem

Sep
21
1 month ago
Activity icon

Started a new Conversation Update Array

i have this values come from form

"explainanswer": {
"53": "yes php framework ",
"54": "not javascript ",
"55": "not security",
"56": "not forensics "
},
"answer": {
"53": "php framework",
"54": "javascript",
"55": "security",
"56": "forensics"
},

i have table answers with this fields

`id`,`answer`, `explain_answer`,

how can update this fields depend on id , id come from table as above 53,54,55,56

i try this code but not work

        foreach ($request->answer as $key=>$val){
            $answer=Answer::findOrFail($key);
            $answer->answer = $request->answer[$key];
            $answer->explain_answer = $request->explainanswer[$key];
            $answer->save();
        }
Activity icon

Started a new Conversation Send Array From Html

<input  type="text" name="question[1]" />
	<textarea name="answer[1]"></textarea>
	<textarea name="answer[1]"></textarea>

<input  type="text" name="question[2]" />
	<textarea name="answer[2]"></textarea>
	<textarea name="answer[2]"></textarea>

in controller when print request->answer

the result is

{
	"1": "aaaa",
	"2": "bbbbb"
}

its give me last value of answer[1] and last value of answer[2],

how can get all value related to answer[$i]

i try to use

        foreach ($request->answer as $v){
            echo $v;
        }

but also not working

Sep
19
1 month ago
Activity icon

Started a new Conversation How To Display Example Code On Your Website

how can hilight code in website,

how laracasts use github-flavored code blocks,

how can add this feature in my website

Sep
16
1 month ago
Activity icon

Started a new Conversation Show Just Not Active Language Mcamara

in mcamara documentation use this code to show all active language

@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
    <li>
        <a rel="alternate" hreflang="{{ $localeCode }}"
            href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
            {{ $properties['native'] }}
        </a>
    </li>
@endforeach

but its show all website language,

I want to show only not an active language, active language must not be shown

ex if site language (en, sp, fr)

and the user now in en lang must show just(sp,fr)

Activity icon

Replied to How Move Laravel Project To Demo Folder

@siangboon i remove all pervious steps, and add prefix, but not working,

i moved public file inside demo folder, but also not working

Activity icon

Started a new Conversation How Move Laravel Project To Demo Folder

i want to move laravel project from

www.abc.com

to

www.abc.com/demo/

i changed baseurl tag

   <base href="https://abc.com/demo/" />

i changed

APP_URL=https://abc.ps/demo/

i changed index.php pathes

require __DIR__.'../../../lcode/vendor/autoload.php';
$app = require_once __DIR__.'../../../lcode/bootstrap/app.php';
$app->bind('path.public', function() {
    return __DIR__;
});

index open successfully

but

images,css,js not working

links not working,

plz how do that

Sep
15
1 month ago
Activity icon

Replied to New Route File Laravel 8

@ismaile let me explain

I used the admin route for the control panel /admin/dashboard /admin/login

I create an admin.php file inside the routes folder used for the admin panel route, all admin route(admin panel) not in web.php but in admin.php I created.

I used a dedicated table for admins, not a user's table.

admins have a login page,different from users page users have a specific login page. admins have a specific login page.

now the problem solved after your help and after the change

   public function handle($request, Closure $next,$guards=null)
    {
        if (Auth::guard($guards)->check()) {
            if($guards == 'admin')
                return redirect(RouteServiceProvider::ADMIN);
            else
                return redirect(RouteServiceProvider::HOME);
        }
        return $next($request);
    }
Activity icon

Replied to New Route File Laravel 8

@ismaile after change


    public function handle($request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;
        if (Auth::guard($guards)->check()) {
            if($guards == 'admin')
                return redirect(RouteServiceProvider::ADMIN);
            else
                return redirect(RouteServiceProvider::HOME);
        }
        return $next($request);
    }

to


    public function handle($request, Closure $next,$guards=null)
    {
        if (Auth::guard($guards)->check()) {
            if($guards == 'admin')
                return redirect(RouteServiceProvider::ADMIN);
            else
                return redirect(RouteServiceProvider::HOME);
        }
        return $next($request);
    }

problem solved

but i dont think this is best idea

Activity icon

Replied to New Route File Laravel 8

thanks @ismaile im sorry for late


my auth.php // i add admin guards and providers
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],

    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admins::class,
        ],

in redirectifauthenticated.php


    public function handle($request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;
        if (Auth::guard($guards)->check()) {
            if($guards == 'admin')
                return redirect(RouteServiceProvider::ADMIN);
            else
                return redirect(RouteServiceProvider::HOME);
        }
        return $next($request);
    }

in routeserviceprovider.php


    public const HOME = '/home';
    public const ADMIN = '/admin/dashboard';
    protected $namespace='App\Http\Controllers';

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));

            Route::prefix('api')
                ->namespace($this->namespace)
                ->middleware('api')
                ->group(base_path('routes/api.php'));
        });
    }

admin.php //new route file


Route::group(['prefix'=>'admin','middleware'=>'guest:admin','namespace'=>'Admin'],function(){
    Route::get('/login','[email protected]')->name('admin.login');
    Route::post('/login','[email protected]')->name('admin.login');
});

new error ErrorException Illegal offset type

Activity icon

Replied to New Route File Laravel 8

thanxs @ismaile

But i got this error

InvalidArgumentException Auth driver [eloquent] for guard [admin] is not defined.

Activity icon

Started a new Conversation New Route File Laravel 8

I want to create a new route file for admins.

in routeServiceProvider.php file

i create this new route inside boot function

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));

            Route::prefix('api')
                ->namespace($this->namespace)
                ->middleware('api')
                ->group(base_path('routes/api.php'));
        });
    }

this code i add


            Route::middleware('admin')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));

in routes folder i create admin.php for routing

but i got this error

Illuminate\Contracts\Container\BindingResolutionException Target class [admin] does not exist.

not see new route file admin.php

Sep
13
1 month ago
Activity icon

Started a new Conversation Protect Videos From Download

im working on an e-learning website. I want to ask if can protect videos from downloading by the student,

how can protect videos from download

Sep
11
1 month ago
Activity icon

Replied to Get Sum Of Rows

@automica thanks for your idea, some modification in code

i add in return


$value->is_correct === 1
$value->is_correct === 2
$value->is_correct === 3

full code

            $numCorrect = $answeredQuestion->filter(function ($value) {
                return $value->is_correct === 1;
            })->count();
Activity icon

Started a new Conversation Get Sum Of Rows

i have this data in answers table

is_marked	is_correct 
	
0 	                2

0 	                2

1 			1

1			1

0			0

1			1

I want to calculate the sum of is marked must return 3.

I want to calculate the sum of is_correct if value =1 //must return 3

I want to calculate the sum of is_correct if value =0 // must return 1

I want to calculate the sum of is_correct if value =2 // must return 2

plz what is the best way without making 4 select statement

Sep
10
1 month ago
Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

@michaloravec but user may can mark questions, to back to it later, so i must save it to db

Activity icon

Started a new Conversation SQLSTATE[23000]: Integrity Constraint Violation: 1452 Cannot Add Or Update A Child Row: A Foreign Key Constraint Fails

i have 2 table


1- answers (`id`, `answer`)

2- student_answers (`id`, `student_id`, `answer_id`)

answer_id in table student_answers is forign_key on id in answers table

when the user select answer, I store answer id in student_answer, but some time user skip question so I sent 0 to answers_id in student_answer, so because 0 does not exist in answers, I got this error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

how can solve this problem

Activity icon

Replied to Find Match In Another Table

@rmcleod79

when the user log in another time to question, it must begin from the last solved question.

what the best query, get all solved( which (is_correct,is_marked)) from student_question

then all unsolved question from the question table

Activity icon

Replied to Find Match In Another Table

not stored, aha i will store it

Activity icon

Replied to Find Match In Another Table

@automica what if user skip some question (answer 1, answer 1, skip 3, answer 4)

Activity icon

Replied to Find Match In Another Table

@automica thx

but not this what i want,

I want from student_question table get all solved question and determine if is_correct, is_marked,

then from questionTable get all unsolved question

Activity icon

Started a new Conversation Find Match In Another Table

i have 2 table

questions('id','question_txt','correct_answer');
student_question('id','question_id','student_id','answer_id','is_marked','is_correct')

a student may solve all question or not,

when the user log in another time to question, it must begin from the last solved question.

what the best query, get all solved( which (is_correct,is_marked)) from student_question

then all unsolved question from the question table

Sep
08
1 month ago
Activity icon

Started a new Conversation Error :PDOException: SQLSTATE[HY000]: General Error: 1366 Incorrect String Value: '\xD8' For Column 'about_ar'

i have this insert statement


        try {
            $units = [];
            foreach ($request->title_ar as $key => $title_ar) {
                $units[] = [
                    'course_id' => $request->course,
                    'title_ar' => $request->title_ar[$key],
                    'title_en' => $request->title_en[$key],
                    'about_ar' => $request->about_ar[$key],
                    'about_en' => $request->about_en[$key],
                    'active' => $request->active,
                    'admin_id' => Auth::id()
                ];
            }

            if (! empty($units)) {
                DB::table('units')->insert($units);
                return redirect('/admin/units')->with('success','تم إضافة الوحدات بنجاح');
            }
        }catch (\Exception $e){
            return $e;
        }

but when insert arabic text in field about_ar[$key] i got this error

error :PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xD8' for column 'about_ar'

Sep
07
1 month ago
Activity icon

Started a new Conversation Return Count Of Expload Values

i have this values 3,4,5,6


to get numbers i used explode
@foreach(explode(',',session()->get('question')['flag_question']) as $flag)
	{{$flag}}
@endforeach

but how can i get count in blade

Activity icon

Replied to How To Append/remove Attribute Value On Click To/from The Comma Separated List Within Hidden Input

@automica it's not working its add id twice for example, if id = 4, will add 44 if the next id is 7 will replace 44 by 77

I want 4,7

Activity icon

Started a new Conversation How To Append/remove Attribute Value On Click To/from The Comma Separated List Within Hidden Input

hi, I have RadioButton with class .answer_question, i want when click on this radio to append value to input hidden with id #correct_question like value="1,2,3,4"

<input type="text" id="correct_question" value="">

var vl = $(this).val();//radio value

correctAnswersArray = correctAnswersArray.includes(vl) ? correctAnswersArray.filter(id => id != vl) : [...correctAnswersArray, vl];

$('#correct_question').val(correctAnswersArray.join(','));

but what happens now. is replace new id not append .

Sep
02
1 month ago
Activity icon

Started a new Conversation Add Class To Div If Value = Specific Number

i have many div with class .questionFollow , i want if .questionFollow Class == id as bellow to addClass text-danger to this class


 $(document).delegate('#MarkQuestion', 'click', function () {
        var id = $(this).attr('data-id');
        var element = $('.questionFollow');
	var classId = element.attr('id');

// if classId equal id ADD .text-danger to thie element

    });

any help

Aug
28
1 month ago
Activity icon

Started a new Conversation Simplify Eloquent Code

in StudentCourse Model table (Pivot Table) i store('active_courses_id','student_id'),

In ActiveCourse i store (id,course_id)

in below query, I want to get all courses not registred to the user ($id),

I use two query, first to get activeCourse that user enrolls on it, then other query go get courses user did not enroll on it depend on the first query.

$userCourse=StudentCourseModel::select('active_courses_id')
   ->where('student_id',$id)
   ->get();
$courses = ActiveCourse::select('id', 'course_id')
   ->with('course:id,title_ar')
   ->where('active', 1)
   ->whereNotIn('id',$userCourse)
   ->get();

i want to ask if any way to use one query instead of two query

Aug
27
2 months ago
Activity icon

Replied to Print Eloquent Result In Blade

yes i have this relatio

public function studentCourse(){
        return $this->belongsTo('App\ActiveCourse','active_courses_id','id');
    }
Activity icon

Replied to Print Eloquent Result In Blade

returned data from eloquent


        $studentCourse = StudentCourseModel::select('active_courses_id')
            ->with(['studentCourse' => function ($q) {
                return $q->select('id','course_id')->with('course:id,title_ar,img');
            }])
            ->where('student_id', $id)
            ->get();
Activity icon

Replied to Print Eloquent Result In Blade

@snapey this is returned data

[
  {
    "active_courses_id": 3,
    "student_course": [
      {
        "id": 3,
        "course_id": 4,
        "course": {
          "id": 4,
          "title_ar": "PHP"
        }
      }
    ]
  },
  {
    "active_courses_id": 4,
    "student_course": [
      {
        "id": 4,
        "course_id": 5,
        "course": {
          "id": 5,
          "title_ar": "e-commerce"
        }
      }
    ]
  }
]

@marianomoreyra 1- first way give me this error

Call to a member function first() on null (View:

2- second way give me this error

Trying to get property 'course' of non-object (View:

Activity icon

Replied to Print Eloquent Result In Blade

thanks, @tykus course have data, as you see in first screen above,

but when print it in blade i got error,

when use

{{ optional($courses->student_course)->course ? $courses->student_course->course->title_ar : '' }}

there is no error, but also no data printed in blade

Activity icon

Started a new Conversation Print Eloquent Result In Blade

i try to print this result in blade using foreach

[
    {
        "active_courses_id": 3,
        "student_course": [
            {
                "id": 3,
                "course_id": 4,
                "course": {
                    "id": 4,
                    "title_ar": "Flutter Course",
                    "img": "[email protected]_7.png"
                }
            }
        ]
    },
    {
        "active_courses_id": 4,
        "student_course": [
            {
                "id": 4,
                "course_id": 5,
                "course": {
                    "id": 5,
                    "title_ar": "E-Commerce Course",
                    "img": "[email protected]_4.png"
                }
            }
        ]
    }
]

in blade

@foreach($studentCourse as $courses)
       <h6>{{ $courses->student_course->course->title_ar }}</h6>
@endforeach

but i got an error

ErrorException

Trying to get property 'course' of non-object (View:

Activity icon

Awarded Best Reply on Insert From Input Text Field Array With Checkbox

This is my final code its works fine.

but I'm not sure if its good or need improve


    public function store(Request $request)
    {
        $question = new Question();
        $question->question=$request->input('question');
        $question->course_id=$request->input('course');
        $question->active=$request->input('active');
        $question->admin_id=Auth::user()->id;
        $question->save();
        $units = [];

        for ($i=0;$i<count($request->answer);$i++){
            $units[] = [
                'question_id' => $question->id,
                'answer' => $request->answer[$i],
            ];
        }

        if (! empty($units)) {

            for($i=0;$i<count($units);$i++){
                $lastId= DB::table('answers')->insertGetId($units[$i]);
            }
            $correct_answer = $lastId-count($units)+$request->correctanswer;
            $question->correct_answer=$correct_answer;
            $question->save();
            return redirect('/admin/question')->with('success','تم إضافة السؤال بنجاح');
        }
    }

in html

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="1">
	<textarea name="answer[]" required></textarea>
</div>

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="2">
	<textarea name="answer[]" required></textarea>
</div>

1- insert question.

2- insert answers and questionid.

3- calculate which answer is the correct answer

4-update question table to take best answer id

Activity icon

Replied to Cant Insert Data To Db: SQLSTATE[23000]: Integrity Constraint Violation: 1452

@sinnbeck


            $student_course=new StudentCourseModel();
            $student_course->active_courses_id=$request->input('course_id');
            $student_course->student_id=$request->input('student_id');
            $student_course->save();

yes i have active_courses row with id 4

Activity icon

Started a new Conversation Cant Insert Data To Db: SQLSTATE[23000]: Integrity Constraint Violation: 1452

active_courses table

        Schema::create('active_courses', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned()->index();
            $table->integer('course_id')->unsigned()->index();
            $table->date('begin_date')->nullable();
            $table->date('end_date')->nullable();
            $table->foreign('course_id')->references('id')->on('courses');
        });

Student table


        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned()->index();
            $table->string("name",40);
            $table->string("email",40)->index()->unique();
        });

in student_course (pivot table) i want to store student with his courses. student_course


        Schema::create('student_course', function (Blueprint $table) {
            $table->bigInteger('active_courses_id')->unsigned();
            $table->bigInteger('student_id')->unsigned();
            $table->foreign('active_courses_id')->references('id')->on('active_courses')->onDelete('cascade');
            $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
        });

migration is fine (No Problem on migration), but when inserting data to student_course I got this error

message: "SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (ikhlaif.student_course, CONSTRAINT student_course_active_course_id_foreign FOREIGN KEY (active_course_id) REFERENCES active_courses (id) ON DELETE CASCADE) (SQL: insert into student_course (active_course_id, student_id) values (4, 47))"

Aug
25
2 months ago
Activity icon

Replied to Insert From Input Text Field Array With Checkbox

This is my final code its works fine.

but I'm not sure if its good or need improve


    public function store(Request $request)
    {
        $question = new Question();
        $question->question=$request->input('question');
        $question->course_id=$request->input('course');
        $question->active=$request->input('active');
        $question->admin_id=Auth::user()->id;
        $question->save();
        $units = [];

        for ($i=0;$i<count($request->answer);$i++){
            $units[] = [
                'question_id' => $question->id,
                'answer' => $request->answer[$i],
            ];
        }

        if (! empty($units)) {

            for($i=0;$i<count($units);$i++){
                $lastId= DB::table('answers')->insertGetId($units[$i]);
            }
            $correct_answer = $lastId-count($units)+$request->correctanswer;
            $question->correct_answer=$correct_answer;
            $question->save();
            return redirect('/admin/question')->with('success','تم إضافة السؤال بنجاح');
        }
    }

in html

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="1">
	<textarea name="answer[]" required></textarea>
</div>

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="2">
	<textarea name="answer[]" required></textarea>
</div>

1- insert question.

2- insert answers and questionid.

3- calculate which answer is the correct answer

4-update question table to take best answer id

Activity icon

Started a new Conversation Insert From Input Text Field Array With Checkbox

i try to insert this form into db

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="0">
	<textarea name="answer[]" required></textarea>
</div>

<div>
	<input class="form-check-input" name="correctanswer" type="radio" value="0">
	<textarea name="answer[]" required></textarea>
</div>

eloquent

        $units = [];
        foreach ($request->answer as $key => $answer) {
            $units[] = [
                'question_id' => $question->id,
                'answer' => $request->answer[$key],
                'correct_answer' => $request->correctanswer[$key],
            ];
        }

        if (! empty($units)) {
            DB::table('answers')->insert($units);
            return redirect('/admin/question')->with('success','تم إضافة السؤال بنجاح');
        }

radio button checked must insert value 1, not checked insert zero. using jquery i changed radio button selected to 1;

but in Eloquent i got this error ErrorException Uninitialized string offset: 1

plz any help to insert (answers and correct answer insert value to 1)

Aug
24
2 months ago
Activity icon

Replied to Insert Array To Database

@sinnbeck @michaloravec Thanks very much

@michaloravec worked but little modify cause $course not array


    public function store(request $request)
    {
        $units = [];

        foreach ($request->title_ar as $key => $title_ar) {
            $units[] = [
                'courses_id' => $request->course,
                'title_ar' => $request->title_ar[$key],
                'title_en' => $request->title_en[$key],
                'admins_id' => Auth::id()
            ];
        }

        if (! empty($units)) {
            DB::table('units')->insert($units);
            return redirect('/admin/units')->with('success','تم إضافة الوحدات بنجاح');
        }
    }
Activity icon

Started a new Conversation Insert Array To Database

i try to insert array value to database , there is no error but data not inserted html

<tr>
    <td>Units Name Fr<span class="required text-danger">*</span></td>
    <td><input type="text" name="title_fr[]" required class="form-control"/></td>
</tr>
<tr>
    <td>Units Name En<span class="required text-danger">*</span></td>
    <td class="entd"><input type="text" name="title_en[]" required class="form-control"/></td>
</tr>

Controller

    public function store(Request $request)
    {
        try {
            $unit=new Units();
            $units = [];
            for ($i = 1; $i < count($request->title_fr); $i++) {
                $units[] = [
                    'courses_id' => $request->course[$i],
                    'title_ar' => $request->title_fr[$i],
                    'title_en' => $request->title_en[$i],
                    'admins_id' => Auth::user()->id,
                ];
            }
            $unit->insert($units);
            return redirect('/admin/units')->with('success','Unit Add Successfully');
        }catch (\Exception $e){
            return $e;
        }
    }
Aug
20
2 months ago
Activity icon

Replied to More Function On Spatie/google Analytics Packages

to getTopOs For Example


    public function fetchTopOs(Period $period, int $maxResults = 10): Collection
    {
        $response = $this->performQuery(
            $period,
            'ga:sessions',
            [
                'dimensions' => 'ga:operatingSystem',
                'sort' => '-ga:sessions',
            ]
        );

        $topOs = collect($response['rows'] ?? [])->map(function (array $osRow) {
            return [
                'operatingSystem' => $osRow[0],
                'sessions' => (int) $osRow[1],
            ];
        });

        if ($topOs->count() <= $maxResults) {
            return $topOs;
        }

        return $this->summarizeTopOS($topOs, $maxResults);
    }
Aug
19
2 months ago
Activity icon

Replied to More Function On Spatie/google Analytics Packages

@sinnbeck TypeError Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in /home4/panorax1/lcode/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 65

Activity icon

Replied to More Function On Spatie/google Analytics Packages

@sinnbeck for example


        $analyticsData = Analytics::performQuery(
            Period::years(1),
            'ga:sessions',
            [
                'metrics' => 'ga:sessions, ga:pageviews',
                'dimensions' => 'ga:yearMonth'
            ]
        );
        return $analyticsData;

but i got error

Activity icon

Started a new Conversation More Function On Spatie/google Analytics Packages

this is the first time I used spatie/google analytics packages to get website visitors

https://github.com/spatie/laravel-analytics

its provide some function, but I want more than that like: 1- total active now and visited pages. 2- country and number of user fore each country.

any help