ethar

Member Since 1 Year Ago

Experience Points
16,120
Total
Experience

3,880 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
115
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

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

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 4
16,120 XP
Jan
17
1 day ago
Activity icon

Replied to Two Column As Unique Value

@tray2 thanks, can you help me, how we can do this in validation

Jan
16
2 days ago
Activity icon

Started a new Conversation Two Column As Unique Value

i have this table

users=>name, country_code, phone_number

how can make (country_code, phone_number) as unique, in migration and validation.

Jan
11
1 week ago
Activity icon

Replied to Custome Error Message (Request Validation)

when remove unique:users,phone',

its return hellow kitty

but when add unique:users,phone', its return index page

Activity icon

Replied to Custome Error Message (Request Validation)

i copy your code and put it on my code

but when add unique:users,phone

its return default laravel index page

Activity icon

Replied to Custome Error Message (Request Validation)

@newbie360

still not working validation for phone

'phone'=>'required|min:10|max:15|unique:users,phone',

users DB

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone')->unique();
        });
    }
Activity icon

Started a new Conversation Custome Error Message (Request Validation)

I make this request file validation

class RegisterRequest extends FormRequest {

    public function authorize() {
        return true;
    }

    public function rules() {
        return [
            'name'=>'required',
            'phone'=>'required|unique|min:10|max:15',
            'gender'=>'required|integer',
            'marital_status'=>'required|integer',
            'birth_date'=>'required|date',
        ];
    }

    public function messages(){
        return [
            'name.required'=>'الرجاء إدخال الإسم',
            'phone.required'=>'الرجاء إدخال رقم الهاتف',
            'phone.unique'=>'رقم الهاتف موجود مسبقاً، بإمكانك تسجيل الدخول بإستخدام رقم الهاتف.',
            'phone.min:10'=>'الرجاء إدخال رقم هاتف صحيح',
            'phone.max:15'=>'الرجاء إدخال رقم هاتف صحيح',
            'gender.required'=>'الرجاء إختيار الجنس',
            'marital_status.required'=>'الرجاء إختيار الحالة الإجتماعية',
            'birth_date.required'=>'الرجاء إدخال تاريخ الميلاد',
        ];
    }
}

in eloquent my code is, i use RegisterRequest instead of Request

    public function store(RegisterRequest $request)
    {
        $user= new User();
        $user->name = $request->name;
        $user->phone = $request->phone;
        $user->gender = $request->gender;
        $user->martial_status = $request->marital_status;
        $user->birth_date = $request->birth_date;
        $user->pin_code = mt_rand(100000, 999999);
        $user->save();
        if($user){
            return $this->successMsg($user);
        }
    }

but custom error message not returned, I got default MySQL error msg, not messages defined in RegisterRequest.

e.g if try to register with an existing phone number I got this MySQL error

Integrity constraint violation: 1062 Duplicate entry '0599888999' for key

not custome error

Jan
09
1 week ago
Activity icon

Started a new Conversation Read Data And Insert It To Db

I work with API, when printing $request echo $request , i got this

flutter: POST /api/confirmPurchase HTTP/1.1
Accept-Encoding: gzip
Content-Length:  460
Content-Type:    text/plain; charset=utf-8
Host:            www.mhpss.test
User-Agent:      Dart/2.10 (dart:io)
{
   "data":[
      {
         "id":21,
         "pid":3,
         "artitle":"hand bag",
         "price":20,
         "size":" LG",
         "color":"#DFA590",
         "pic":"/images/products/bag_1_3.png",
         "qty":1
      },
      {
         "id":20,
         "pid":3,
         "artitle":"tshirt",
         "price":20,
         "size":" XS ",
         "color":"#8B8586",
         "pic":"/images/products/bag_1_3.png",
         "qty":1
      },
   ]
}

when try to print data echo $request->data i got nothing.

any way to read this data and insert it to db.

Jan
04
2 weeks ago
Activity icon

Started a new Conversation 1055 Expression #1 Of SELECT List Is Not In GROUP BY Clause And Contains Nonaggregated Column

i have chat_msgs table it contains ( body, type, from_id, to_id, )

i want to group by from_id, my Eloquent

    public function index()
    {
        $chatMsgs=ChatMsg::select('id','body','from_id','to_id')
            ->where('to_id',Auth()->user()->id)
            ->with('user:id,name')
            ->groupBy('from_id')
            ->get();
        return $chatMsgs;
    }

but I got this error SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mhpss.chat_msgs.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select id, body, from_id, to_id from chat_msgs where to_id = 1 group by from_id)

I try to use

public function index()
{
    $chatMsgs=ChatMsg::select('id','body','from_id','to_id')
        ->where('to_id',Auth()->user()->id)
        ->with('user:id,name')
        ->groupBy('from_id','id')
        ->get();
    return $chatMsgs;
}
but I got all record without groubing
Dec
29
2 weeks ago
Activity icon

Started a new Conversation Mutators Not Work

i have this mutator, check if value is True , insert 1 to db, if not insert 0

    public function setHiddenNameAttribute($value)
    {
        if($value == True){
            $this->attributes['hidden_name'] = 1;
        }else if($value == False){
            $this->attributes['hidden_name'] = 0;
        }
    }

eloquent

$ques->hidden_name = $request->display_name;

but aways 1 is inserted to db, eloquent ignore mutators

Dec
17
1 month ago
Activity icon

Replied to Get Data From Another Model

@tykus i got this error

Trying to get property 'day' of non-object (View: /Library/WebServer/Documents/mhpss/resources/views/admin/clinics/indexclinics.blade.php)

Activity icon

Started a new Conversation Get Data From Another Model

i have this model

class Clinic extends Model
{
    public function clinkDay(){
        return $this->hasOne('App\Models\ClinkDay');
    }
}

and another model to specify days of clinic

class ClinkDay extends Model
{
    public function clinic(){
        return $this->belongsTo('App\Models\Clinic');
    }
}

in eloquent

        $clinics=Clinic::select('id','title','admin_id','active','doctor_id','created_at')
            ->with('admin:id,name')
            ->with('doctor:id,name_ar,major_ar,thumb')
            ->with('clinkDay:clinic_id,day,from,to')
            ->orderBy('id','DESC')
            ->paginate(13);

in eloquent everything is ok,

but in Clinik Model I want to reach the day field that exist in ClinkDay

i try to use this

    public function getDay()
    {
        return $this->day;
    }

but doesn't work

any way to reach day field in clinkDay

Nov
30
1 month ago
Activity icon

Replied to Get Specific Fields From Laravel API Resource Collection

@vincent15000 not working i got this error ErrorException: Non-static method Illuminate\Database\Eloquent\Model::only()

Activity icon

Started a new Conversation Get Specific Fields From Laravel API Resource Collection

i have this CatResource

return [
    'id' => $this->id,
    'title' => $this->title,
    'desc' => $this->desc,
    'active' => $this->getActive(),
    'admin'=> $this->admin,
    'tags'=> $this->tags,
    'created_at' => $this->created_at->toDateString(),
];

in query i use

return CatResource::collection(
    Cat::with('admin:id,name')
        ->orderBy('id','DESC')
        ->paginate(13)
);

i get this array

{
    "data": [
        {
            "id": 22,
            "title": "Omnis quia nihil lab",
            "desc": "Quibusdam tempore q",
            "active": "<span class=\"text-success\">مفعل</span>",
            "admin": {
                "id": 1,
                "name": "إيثار"
            },
            "tags": "Ullamco qui enim des",
            "created_at": "2020-11-28"
        },
    ]
}

until know every thing is ok. but in some case i wat to return just

{
    "data": [
        {
            "id": 22,
            "title": "Omnis quia nihil lab",
        },
    ]
}

the question of how can do that get just a specific field not all key in the resource file, without creating a new resource file

Nov
29
1 month ago
Activity icon

Started a new Conversation Update Select Box Vue Js

i have this active value in vue js

data(){
        return{
            fields:{
                active:'',
            }
        }
    },

i want if active = 1 to print this

<select class="form-control" required="" v-model="fields.active">
          <option value="1">active</option>
           <option value="0">in active</option>
</select>

but if active = 0

 <select class="form-control" required="" v-model="fields.active">
              <option value="0">in active</option>
              <option value="1">active</option>
</select>
Nov
28
1 month ago
Activity icon

Replied to Error In Laravel API Resource

@michaloravec after refactoring i got this error

BadMethodCallException
Call to undefined method App\Models\Admin::mapInto()
http://www.vuecms.test/api/cats
Activity icon

Started a new Conversation Error In Laravel API Resource

i want to get cat with admin who create the cat

in catController

    public function index()
    {
        $cats=Cat::with(['admin.cat'])->get();
        return CatResource::collection($cats->paginate(13));
    }

in catModel

    public function admin(){
        return $this->belongsTo('App\Models\Admins');
    }

in adminModel

    public function cat(){
        return $this->hasMany('App\Models\Cat');
    }

in catResource

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'desc' => $this->desc,
            'active' => $this->getActive(),
            'admin'=> AdminResource::collection($this->whenLoaded('admin')),
            'created_at' => $this->created_at,
        ];
    }

in adminResource

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'cat' => CatResource::collection($this->whenLoaded('cat')),
        ];
    }

but i got this error

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cats.admins_id' in 'where clause' (SQL: select * from `cats` where `cats`.`admins_id` in (1))

why in select cats.admins_id it must be cats.admin_id

i reanamed admins Model to admin bu i got this error

BadMethodCallException
Call to undefined method App\Models\Admin::mapInto()
http://www.vuecms.test/api/cats
Nov
24
1 month ago
Activity icon

Replied to Vue Js With Laravel 8 Route Error

same problem, i use laravel 8

Activity icon

Started a new Conversation Vue Js With Laravel 8 Route Error

i use apiResource to submit data but i got an error

in api.php

Route::apiResource('posts', PostController::class);

in vuejs file create.vue

    methods:{
        submitData(){
            axios.post('api/posts',this.fields).then(res=>{
                this.$router.push('/');
            });
        }
    }

but i got this error

{message: "", exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",…}
exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
file: "/Library/WebServer/Documents/LaraVue/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php"
line: 43
message: ""
Activity icon

Replied to Register Component In Vue.js

@rodrigo.pedra another question how can register component locally

Activity icon

Started a new Conversation Register Component In Vue.js

i try to make seperate component for cardDesign to use it in all pages, CardUi.vue

<template>
    <div class="card">
        fads
        <h4>{{ cardHeader }}</h4>
        <slot></slot>
    </div>
</template>
<script>
export default {
    props:['cardHeader']
}
</script>

in app.js

import CardUi from './components/UI/CardUi';

in crate.vue to use this compunennt

    <card-ui></card-ui>

but i got this error

    |                              
  3  |  <card-ui></card-ui>
     |  ^^^^^^^^^^^^^^^^^^^
  4  |  

 @ ./resources/js/components/Posts/Create.vue?vue&type=template&id=2df8d6c3& 1:0-216 1:0-216
 @ ./resources/js/components/Posts/Create.vue
 @ ./resources/js/app.js
 @ multi ./resources/js/app.js ./resources/css/app.css
Nov
09
2 months ago
Activity icon

Replied to Deference Between Dates Laravel

@michaloravec but if end_date = 2020-09-20 its reutn 50 not -50 can i get days in minus if date finished

Activity icon

Replied to Deference Between Dates Laravel

@michaloravec thanks

but another help if you can how can I get how different in days

Activity icon

Started a new Conversation Deference Between Dates Laravel

I want to get the difference between now and the future date

    public function getDiffInDaysAttribute()
    {
        $dif= Carbon::now()->diffInDays($this->end_date);
        if($dif > 0){
            return 'Running';
        }else{
            return 'Finished';
        }
    }

I use this code but always return Running but if end_date == 2020-05-06 its return Running but must be return finished

Sep
27
3 months 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
3 months 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
3 months 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
3 months 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
3 months 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
4 months 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
4 months 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
4 months 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
4 months 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
4 months 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