Friday, March 31, 2017

Laravel output single row from database

I am a beginner at Laravel, and I am stuck :)

I am building a simple CMS for a costumer with a rather simple website. I have created a database for all the text throughout the site, which I want to be able to edit. All the CRUD is working, but I can't seem to output the content from the database, with blade, to the actual view, as I get the error that the variable doesnt exist.

I thought I would be doing something like this My table has strings for id's to identify the respective text-content thoughout the site.

I have a MainController and a TextController, which is the one dealing with the CRUD of the text-elements.

I am probably forgetting a simple thing, but I just can't seem to work it out.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Text;
use Session;

class TextController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $texts = Text::all();

    return view('texts.index')->withTexts($texts);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text = new Text;
    $text->content = $request->content;
    $text->save();


    return redirect()->route('texts.index');
}


/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $text = Text::find($id);
    return view('texts.edit')->withText($text);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $text = Text::find($id);
    $this->validate($request, array(

        'content' => 'required'
        ));

    $text->content = $request->content;
    $text->save();

    Session::flash('success', 'Teksten blev ændret!');

    return redirect()->route('texts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    //
}

}

I would think that I am missing something in the MainController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use Illuminate\Support\Facades\DB;
use Session;
use App\Text;


class MainController extends Controller
{
public function index(){

    return view('index');
}

Could that be?

Thanks in advance!



via Camilla Holst

Advertisement