1

I wrote some code learn from a php/laravel video tutorial . but the result is not the same. the problem step is:

  1. create a db table named questions and a model named Question.
  2. add a function to save data into db.
  3. in this function, use bellow code:

    use Illuminate\Database\Eloquent\Model;
    
    class Question extends Model
    {
        public function add_question(){
            $this->title = rq('title');
            $this->user_id = session('user_id');
            if(rq('description'))
                $this->desc = rq('description');
            $result = $this->save();
            //dump($result);
            return( $result)?
                 ['status'=> '1' , 'id'=>$this->id] :
                 ['status'=> '0' , 'message'=>'db save fail'];
        }
    }
    
  4. run in browser http://localhost/api/question/add?title=rrrrr&description=tttttt and check db, there will be two same records. like bellow:

    id  title   descdescription  user_id    status  created_at       updated_at
    12  rrrrr   tttttt           18         ok      2019/4/7 16:55   2019/4/7 16:55
    13  rrrrr   tttttt           18         ok      2019/4/7 16:55   2019/4/7 16:55
    

    it is not same result as it is in the video tutorial.

  5. if I uncomment dump($result); , it will insert 1 record normally.

I am using wampserver on windows, PHP version is 7.3.1. I am a freshman on PHP. So I don't know what is the problem.

rq() is in web.php

function rq($key=null, $default=null){
    if(!$key)return Request::all();
    return Request::get($key,$default);
}

    function question_ins(){
        return new App\Question;
    }

    Route::any('api/question/add', function () {

        return(question_ins()->add_question());
    });
J.S
  • 15
  • 5
  • Could you provide more context about where this conditionals is being used? – mdexp Apr 07 '19 at 17:35
  • hi mdexp, I add whole function . please take a look. thanks – J.S Apr 07 '19 at 17:42
  • Could you please provide the controller action or route closure/function (if you have one) that calls the `add_question` method. The ternary statement (using `?` and `:`) is the same as the conditional statement (using `if` and `else`) from a programming standpoint, so your code will work exactly the same in both cases. Also where is the `rq()` function defined? The tutorial you're following doesn't seem to guide you into doing things properly, because in general the method `add_question` should not be part of your model class. – Bogdan Apr 07 '19 at 17:55
  • hi Bogdan, you are right, I test again, and find the difference. please check updated question. Will it be browser-related? But I check it with ie and chrome, both same problem. – J.S Apr 07 '19 at 18:17
  • OMG, it acts different on different browser. I check it with Mozilla, it won't happen, why? – J.S Apr 07 '19 at 18:23
  • if I add "dump($result);", it can work properly on ie and chrome, but no matter add dump() or not, it can work well on mozilla. Does anyone know what is the problem? – J.S Apr 07 '19 at 18:26
  • Could you please provide a link to the tutorial you're following. – Bogdan Apr 07 '19 at 18:30
  • sorry it is a china website and it is paid video. the code is the same, but the teacher use a mac PC. – J.S Apr 08 '19 at 02:09
  • Welcome J.S to Stack Overflow! As @Bogdan pointed out, there's a sneaky suspicion that your tutorial isn't steering you down the right path. I recommend reading up on [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) and [RESTful](https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming) applications. – FullStackOfPancakes Apr 08 '19 at 02:32
  • As for your question, the [Laravel docs](https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models) on inserting and updating Eloquent models should help you out here. – FullStackOfPancakes Apr 08 '19 at 02:33

1 Answers1

0

create a db table named questions and a model named Question.

Read about defining Models here

From your CLI:

php artisan make:model Question --migration

Edit your Question Model:

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    // Just tweak this for whatever your Model looks like 
    protected $fillable = [
        'subject',
        'body',
        'author'
    ];

}

Edit your create_questions_table migration:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateQuestionsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('questions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body');
            $table->string('subject');
            $table->string('author');
            $table->timestamps();
        });
     }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('questions');
    }

}

From your CLI, run php artisan migrate

add a function to save data into db.

Check out the Laravel docs on Controllers and what you can do with them.

Again from your CLI:

php artisan make:controller QuestionController

QuestionController:

<?php

namespace App\Http\Controllers;
use App\Question;
use Illuminate\Http\Request;

class QuestionController extends Controller {

    public function store( Request $request )
    {

        // Create a new instance of your Question Model
        //modify input param .
        $question = App\Question::firstOrNew([
            'body' => $request->body,
            'subject' => $request->subject,
            'author' => $request->author
        ]);

        // Then save it to the database
        $question->save();

        return back()->with('success', 'Question posted');

    }

}

Question.blade.php

<form method="POST" action="/question">
    @csrf 
    <input type="text" name="body" id="body" class="form-control">
    <input type="text" name="subject" id="subject" class="form-control">
    <input type="text" name="author" id="author" class="form-control">
    <button class="btn btn-primary">Ask Question</button>
</form>

@if( session('success') )
    <div class="alert alert-success">
        <h3>Question asked!</h3>
    </div>
@endif 

Routes/web.php

Route::post('/question', QuestionController@store)->name('ask-question');
FullStackOfPancakes
  • 1,167
  • 10
  • 22
  • hi , thanks for your help, I follow your instruction. it works well. – J.S Apr 08 '19 at 16:27
  • hi,@UkraineInTheMembrane, am I right to change input param of firstOrNew() to as bellow:$question = Question::firstOrNew( ['body' => $request->body, 'subject' => $request->subject, 'author' => $request->author] ); I got db insert error using your code. after changing it. it inserts db well. – J.S Apr 08 '19 at 16:48
  • Of course @J.S ! That was my mistake - I'll edit my answer. You can read more [here](https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models) about using Eloquent to insert / create records. – FullStackOfPancakes Apr 08 '19 at 16:56
  • Hey @J.S - if this solved your problem, would you mind accepting the answer? Much appreciated! – FullStackOfPancakes Apr 08 '19 at 20:59