Rik van Toorn
Rik van Toorn

Reputation: 15

Can't get data from database - Laravel

I have a very simple and short code more or less directly from a course but it doesnt work. I get an error nobody seemingly had before because I can't find a single webpage where my exact error is mentioned.

I'm just trying to get data from my (sql) database in a controller with Laravel. Controller:

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Joke as Joke;


class ContentsController extends Controller
{

public function __construct( Joke $joke )
{
    $this->joke = $joke;
}
//
public function index()
{
    $data = [];
    $data = ['jokes'] = $this->joke->all();


    return view('index', $data);
}
}

DB migration:

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

class CreateJokesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('jokes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('joke');
        $table->integer('upvotes');
        $table->integer('downvotes');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
    });
}

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

When I try to run it I get this error: "Assignments can only happen to writable values" and its exactly on the line with $data = ['jokes'] = $this->joke->all();

I'm totally lost.

Upvotes: 1

Views: 1077

Answers (1)

Jonathon
Jonathon

Reputation: 16283

What you're doing is trying to assign the result of $this->jokes->all(), to ['jokes'], which is not a variable, as well as $data, which is:

$data = ['jokes'] = $this->joke->all();

You can't do that in PHP (Or any programming language as far as I am aware). It's just like trying to do something like 1 = 'this is not number 1';. PHP is complaining about it.

I get the feeling you've just added an extra =, where there shouldn't be and your code should look like this:

$data['jokes'] = $this->joke->all();

This assigns $this->joke->all() to an array item with the key jokes, which is probably what you want.

Upvotes: 1

Related Questions