Laravel-Bootstrap Starter Site content management - php

I am currently working with the starter site here:
https://github.com/andrewelkins/Laravel-4-Bootstrap-Starter-Site
Any html I put as blog post gets converted to text. For example, tag hi tag(should have brackets around tag) get converted into hi within a div. I want it to just output hi in a tag like a div
Here is the Controller
<?php
class AdminBlogsController extends AdminController {
/**
* Post Model
* #var Post
*/
protected $post;
/**
* Inject the models.
* #param Post $post
*/
public function __construct(Post $post)
{
parent::__construct();
$this->post = $post;
}
/**
* Show a list of all the blog posts.
*
* #return View
*/
public function getIndex()
{
// Title
$title = Lang::get('admin/blogs/title.blog_management');
// Grab all the blog posts
$posts = $this->post;
// Show the page
return View::make('admin/blogs/index', compact('posts', 'title'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function getCreate()
{
// Title
$title = Lang::get('admin/blogs/title.create_a_new_blog');
// Show the page
return View::make('admin/blogs/create_edit', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function postCreate()
{
// Declare the rules for the form validation
$rules = array(
'title' => 'required|min:3',
'content' => 'required|min:3'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
// Create a new blog post
$user = Auth::user();
// Update the blog post data
$this->post->title = Input::get('title');
$this->post->slug = Str::slug(Input::get('title'));
$this->post->content = Input::get('content');
$this->post->meta_title = Input::get('meta-title');
$this->post->meta_description = Input::get('meta-description');
$this->post->meta_keywords = Input::get('meta-keywords');
$this->post->user_id = $user->id;
// Was the blog post created?
if($this->post->save())
{
// Redirect to the new blog post page
return Redirect::to('admin/blogs/' . $this->post->id . '/edit')->with('success', Lang::get('admin/blogs/messages.create.success'));
}
// Redirect to the blog post create page
return Redirect::to('admin/blogs/create')->with('error', Lang::get('admin/blogs/messages.create.error'));
}
// Form validation failed
return Redirect::to('admin/blogs/create')->withInput()->withErrors($validator);
}
/**
* Display the specified resource.
*
* #param $post
* #return Response
*/
public function getShow($post)
{
// redirect to the frontend
}
/**
* Show the form for editing the specified resource.
*
* #param $post
* #return Response
*/
public function getEdit($post)
{
// Title
$title = Lang::get('admin/blogs/title.blog_update');
// Show the page
return View::make('admin/blogs/create_edit', compact('post', 'title'));
}
/**
* Update the specified resource in storage.
*
* #param $post
* #return Response
*/
public function postEdit($post)
{
// Declare the rules for the form validation
$rules = array(
'title' => 'required|min:3',
'content' => 'required|min:3'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
// Update the blog post data
$post->title = Input::get('title');
$post->slug = Str::slug(Input::get('title'));
$post->content = Input::get('content');
$post->meta_title = Input::get('meta-title');
$post->meta_description = Input::get('meta-description');
$post->meta_keywords = Input::get('meta-keywords');
// Was the blog post updated?
if($post->save())
{
// Redirect to the new blog post page
return Redirect::to('admin/blogs/' . $post->id . '/edit')->with('success', Lang::get('admin/blogs/messages.update.success'));
}
// Redirect to the blogs post management page
return Redirect::to('admin/blogs/' . $post->id . '/edit')->with('error', Lang::get('admin/blogs/messages.update.error'));
}
// Form validation failed
return Redirect::to('admin/blogs/' . $post->id . '/edit')->withInput()->withErrors($validator);
}
/**
* Remove the specified resource from storage.
*
* #param $post
* #return Response
*/
public function getDelete($post)
{
// Title
$title = Lang::get('admin/blogs/title.blog_delete');
// Show the page
return View::make('admin/blogs/delete', compact('post', 'title'));
}
/**
* Remove the specified resource from storage.
*
* #param $post
* #return Response
*/
public function postDelete($post)
{
// Declare the rules for the form validation
$rules = array(
'id' => 'required|integer'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
$id = $post->id;
$post->delete();
// Was the blog post deleted?
$post = Post::find($id);
if(empty($post))
{
// Redirect to the blog posts management page
return Redirect::to('admin/blogs')->with('success', Lang::get('admin/blogs/messages.delete.success'));
}
}
// There was a problem deleting the blog post
return Redirect::to('admin/blogs')->with('error', Lang::get('admin/blogs/messages.delete.error'));
}
/**
* Show a list of all the blog posts formatted for Datatables.
*
* #return Datatables JSON
*/
public function getData()
{
$posts = Post::select(array('posts.id', 'posts.title', 'posts.id as comments', 'posts.created_at'));
return Datatables::of($posts)
->edit_column('comments', '{{ DB::table(\'comments\')->where(\'post_id\', \'=\', $id)->count() }}')
->add_column('actions', '<a href="{{{ URL::to(\'admin/blogs/\' . $id . \'/edit\' ) }}}" class="btn btn-default btn-xs iframe" >{{{ Lang::get(\'button.edit\') }}}</a>
{{{ Lang::get(\'button.delete\') }}}
')
->remove_column('id')
->make();
}
}
Here is the Model
<?php
use Illuminate\Support\Facades\URL;
class Post extends Eloquent {
/**
* Deletes a blog post and all
* the associated comments.
*
* #return bool
*/
public function delete()
{
// Delete the comments
$this->comments()->delete();
// Delete the blog post
return parent::delete();
}
/**
* Returns a formatted post content entry,
* this ensures that line breaks are returned.
*
* #return string
*/
public function content()
{
return nl2br($this->content);
}
/**
* Get the post's author.
*
* #return User
*/
public function author()
{
return $this->belongsTo('User', 'user_id');
}
/**
* Get the post's meta_description.
*
* #return string
*/
public function meta_description()
{
return $this->meta_description;
}
/**
* Get the post's meta_keywords.
*
* #return string
*/
public function meta_keywords()
{
return $this->meta_keywords;
}
/**
* Get the post's comments.
*
* #return array
*/
public function comments()
{
return $this->hasMany('Comment');
}
/**
* Get the date the post was created.
*
* #param \Carbon|null $date
* #return string
*/
public function date($date=null)
{
if(is_null($date)) {
$date = $this->created_at;
}
return String::date($date);
}
/**
* Get the URL to the post.
*
* #return string
*/
public function url()
{
return Url::to($this->slug);
}
/**
* Returns the date of the blog post creation,
* on a good and more readable format :)
*
* #return string
*/
public function created_at()
{
return $this->date($this->created_at);
}
/**
* Returns the date of the blog post last update,
* on a good and more readable format :)
*
* #return string
*/
public function updated_at()
{
return $this->date($this->updated_at);
}
}
Thank you in advanced for your help!

This is because the output within the views you are using, is being ran through htmlentities via the blade curly braces {{{ }}}, meaning;
<div>hi </div>
is converted into
<<div>hi </div>
To prevent this and to allow html within posts, change the {{{ }}} to {{ }}.

You have two solutions here:
you can either find in which file the content is being encoded and remove the code that's doing the encoding
or whenever you need to output a value that's encoded, just decode it using HTML::decode(). So for an encoded post content you can write in yout view HTML::decode($post->content).

Related

Laravel Policy bug

I have used Laravel Policies successfully in the past but am having issues with one currently.
In an ArticleController I have the following method:
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create', Article::class);
$categories = $this->categories;
return view('editable.news.create', compact('categories'));
}
My ArticlePolicy looks like this:
<?php
namespace App\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use App\User;
use App\Article;
class ArticlePolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine whether the user can view the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function show(User $user, Article $article)
{
// If the article is published
if ($article->published) {
return true;
}
// A user with permission can view unpublished articles
if ($user->can('view unpublished articles')) {
return true;
}
// Authors can view their own unpublished posts
if ($user->username === $article->author->username) {
return true;
}
}
/**
* Determine whether the user can create posts.
*
* #param \App\User $user
* #return mixed
*/
public function create(User $user)
{
return true;
}
/**
* Determine whether the user can update the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function update(User $user, Article $article)
{
if ($user->can('edit own articles')) {
return $user->username === $article->author->username;
}
if ($user->can('edit any articles')) {
return true;
}
}
/**
* Determine whether the user can delete the post.
*
* #param \App\User $user
* #param \App\Post $post
* #return mixed
*/
public function delete(User $user, Article $article)
{
// A user can delete their own articles
if ($user->can('delete own articles')) {
return $user->username === $article->author->username;
}
// A user with permission can delete any article
if ($user->can('delete any articles')) {
return true;
}
}
}
You can see in the create method I am just returning true, this is deliberate.
Whenever I hit the create blade I always receive a 403 error.
I also have an accompanying test:
/** #test */
public function a_user_with_permission_can_create_an_article()
{
$this->setupPermissions();
$user = factory(User::class)->create();
$user->assignRole('news contributor');
$article = factory(Article::class)->raw(['excerpt' => null]);
$this->actingAs($user)
->get(route('thanos.articles.create'))
->assertStatus(200);
$this->post(route('thanos.articles.store'), $article);
$this->assertDatabaseHas('articles', [
'user_username' => $user->username,
'title' => $article['title']
]);
}

laravel route and controller

i am a new laravel user and a have admin page which doing update delete and insert my problem is i dont know how to call this functions in route.
Note: all this options working on one page (admin).
so please can anyone help me ?!
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
class BlogPostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(){
$date = date('Y-m-d');
$time = time('H:i:s');
/*$sections = ['History' => 'history.png','Electronics' => 'electronics.png','Electrical' => 'electrical.png','Science' => 'science.png',
'Art'=>'ARt.png','Database'=>'database.png','Irrigation'=>'irrigation.png','Novel'=>'Novel.png','Style'=>'Stsyle.png'];
*/
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.library')->withSections($sections)->withDate($date)->withTime($time);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(){
//return View::make('posts.create');
return '<center><h1>Creating new section in the library!</h1></center>';
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store( Request $request){
$section_name = $request->input('section_name');
$file = $request->file('image');
$destinationPath = 'images';
$filename = $file->getClientOriginalName();
$file->move($destinationPath,$filename);
DB ::table('sections')->insert(['section_name'=>$section_name,'image_name'=>$filename]);
return redirect('admin');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id){
// $post = Post::find($id);
// return View::make('posts.show')->with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id){
// $post = Post::find($id);
// return View::make('posts.edit')->with('post', $post);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id,Request $request){
$section_name = $request->input('section_name');
DB ::table('sections')->where('id',$id)->update(['section_name'=>$section_name]);
return redirect('admin');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id){
DB :: table('sections')->where('id',$id)->delete();
return redirect('admin');
}
public function admin()
{
$sections = DB ::table('sections')->get();
return view('libraryViewsContainer.admin',['sections'=>$sections]);
}
}
Not entirely sure of the question, but you list the routes in routes.php, under the web group (so it applies default checks).
When you have resources, they'll use CRUD operations (create, read, update, delete) and will correspond to the default operates in the class. Else, make your own function names, and put seperate routes.
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('/user', 'UserController');
}
Another option is calling the method direct in your routes:
Route::get('/auth/login', '\App\Http\Controllers\Auth\AuthController#getLogin');
Route::any('/datafeed/{id}/validate', 'DataFeedController#validateQuery');
You'll notice {id} which is the variable available in the function you've selected i.e. function validateQuery($id);
Here's a full example:
class UserController extends BaseController
{
public function __construct(User $model)
{
parent::__construct($model);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$collection = $this->model->all();
return view('user.index')->with('collection', $collection);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('user.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->create($input);
return redirect()->action('UserController#show', [$connector->id]);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$connector = $this->model->findOrFail($id);
return view('user.show')->with('connector', $connector);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$connector = $this->model->findOrFail($id);
return view('user.edit')->with('connector', $connector);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = Input::except(['_method', '_token']);
$connector = $this->model->findOrFail($id);
$connector->update($input);
return redirect()->action('UserController#show', [$id]);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$currentID = Auth::user();
$user = $this->model->findOrFail($id);
if ($currentID->id != $user->id) {
$user->delete();
} else {
Session::flash('flash_message', "You cant delete your own account!");
Session::flash('flash_type', 'alert-danger');
}
return redirect()->action('UserController#index');
}
And another example with a custom route:
Route::any('/datafeed/{id}/execute', 'DataFeedController#execute');
public function execute($id, $test = false) {
$results = $this->executeQuery($id, $test);
return view('datafeed.execute')->with('results', $results);
}
I'm not entirely sure on your plans (or even if you've fully read the documentation?) but you can access these functions by doing something similar to the following in your routes.php or Routes\web.php (depending on your version) file:
Route::get('/blog/create', 'BlogPostController#create');
Route::get('/blog/article/{id}', 'BlogPostController#show');
The first part is defining the route and the second part is saying what method should be run on the defined controller when this route is matched in the address bar. It doesn't always have to be get requests though, you can do get, post, patch and put

Laravel: Can't get post form

Me and my partner have been working a combined period of almost 11 hours trying to figure this out but we just can't seem to crack it.
We're building a web forum application in which users are able to make their own threads. We managed to get edit to work, although redirect still doesn't work right yet. We have an online preview over at http://detune-niuwang.c9users.io/
If you try using the 'New Thread' page and click on the submit button, it will just delete anything typed into the form and checking back on the Frontpage, no threads would have been created. The Edit functionality works though.
Here are some snippets of our code:
Routes.php
Route::resource('posts', 'Channel\Post\Posts');
Route::get('/', 'Channel\Post\Posts#index');
Controllers\Channel\Post\Posts.php
/**
* Show the form for creating a new post.
*
* #return Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store the newly created post
*
* #param PostRequest $request
* #return Response
*/
public function store(PostRequest $request)
{
$postData = $this->post->create(['title', 'content']);
if($this->post->create($postData)) {
return redirect()->back()->withSuccess('Post successfully created.');
}
return redirect()->back()->withError($postData);
}
create.blade.php
#extends('_shared.master')
#section('title')
Create New Post
#endsection
#section('content')
<div class="panel panel-default">
<div class="panel-heading">New Thread</div>
<div class="panel-body">
{!! Form::open(['route' => 'posts.store', 'class' => 'form-horizontal'])!!}
#include('posts.form')
{!! Form::close() !!}
</div>
</div>
#stop
Models\Channel\Post\Post.php
<?php
namespace Detune\Models\Channel\Post;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* The database table used by the Model.
*
* #var string
*/
protected $table = 'posts';
/**
* The attributes that are mass assignable
*
* #var array
*/
protected $fillable = ['title', 'content', 'created_at'];
}
Repositories\PostRepository.php
<?php
namespace Detune\Repositories\Post;
use Detune\Models\Channel\Post\Post;
use Illuminate\Database\Eloquent\Collection;
/**
* Class PostRepository
* #Package Detune\Repository
*/
class PostRepository implements PostRepositoryInterface {
/**
* #var Post;
*/
protected $post;
/**
* #param Post $post
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* Create New Post
*
* #param array $postData
* #return Post|null
*/
public function create(array $postData)
{
return $this->post->create($postData);
}
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter)
{
return $this->post->paginate($filter['limit']);
}
/**
* Get Post by ID
*
* #param $id
* #return Post
*/
public function find($id)
{
return $this->post->find($id);
}
}
Repositories\PostRepositoryInterface.php
<?php
namespace Detune\Repositories\Post;
use Detune\Models\Channel\Post;
use Illuminate\Database\Eloquent\Collection;
/**
* Interface PostRepositoryInterface
* #package Detune\Repository
*/
interface PostRepositoryInterface {
/**
* Create New Post\
*
* #param array $postData
* #return Post
*/
public function create(array $postData);
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter);
/**
* Get Post by ID
* #param $post_id
* #return Post
*/
public function find($id);
}
Services\Post\PostService.php
<?php
namespace Detune\Services\Post;
use Detune\Services\Service;
use Illuminate\Contracts\Logging\Log;
use Illuminate\Support\ServiceProvider;
use Detune\Repositories\Post\PostRepositoryInterface;
/**
* Class PostService
* #package Detune\Services\Post
*/
class PostService extends Service {
/**
* #var PostRepositoryInterface
*/
protected $post;
/**
* #var Log
*/
protected $logger;
/**
* #param PostRepositoryInterface $post
* #param Log $logger
*/
public function __construct(PostRepositoryInterface $post, Log $logger)
{
$this->post = $post;
$this->logger = $logger;
}
/**
* Create New Post
*
* #param array $postData
* #return Post | null
*/
public function create()
{
try{
return $this->post->create($postData);
} catch (\Exception $e) {
$this->logger->error('Post->create: ' . $e->getMessage());
return null;
}
}
/**
* Post Pagination
*
* #param array $filter
* #return collection
*/
public function paginate(array $filter =[])
{
$filter['limit'] = 20;
return $this->post->paginate($filter);
}
/**
* Update the Post
*
* #param array $id
* #param array $postData
* #return bool
*/
public function update($id, array $postData)
{
try{
$post = $this->post->find($id);
$post->title = $postData['title'];
$post->content = $postData['content'];
return $post->save();
} catch (\Exception $e) {
$this->logger->error('Post->update: ' . $e->getMessage());
return false;
}
}
/**
* Delete Post
*
* #param $id
* #return mixed
*/
public function delete($id)
{
try {
$post = $this->post->find($id);
return $post->delete();
} catch (\Exception $e){
$this->logger->error('Post->delete: ' . $e->getMessage());
return false;
}
}
/**
* Get Post by ID
*
* #param $id
* #return Post
*/
public function find($id)
{
try {
return $this->post->find($id);
} catch (\Exception $e) {
$this->logger->error('Post->find: ' .$e->getMessage());
return null;
}
}
}
Any help with this are appreciated :)
The create method on an Eloquent model is normally a static method. In your code it seems to be called as if it's an instance method.
I believe you have (at least) 3 options.
Change your create call into an insert call. (I don't think this will return an instance of the Post model, just a boolean).
Call it statically Post::create($postData);
Use the newInstance method
$post = $this->post->newInstance($postData);
return $post->save() ? $post : null;

Why would a laravel route work, passing parameters, when used as a link but not when used in a redirect, generating a missing argument 1 error?

Routes - I have 2 routes related to this
Route::resource('items', 'ItemsController');
Route::get('process/{process}/items', 'ItemsController#index');
When I use the 2nd, the index function (in the controller mentioned above) picks up the process id and runs without a hitch.
This is the link on a separate view which uses the 2nd route listed above:
{{ HTML::link('process/'.$process->id.'/items', 'Manage Items', array('class' =>'btn btn-primary')) }}
When I use a redirect from the update function in the same controller I get
"Missing argument 1 for ItemsController::index()"
which is the function that accepts the parameter so it can display all the items with that id.
It doesn't seem to matter what I use. Here are some of the statements I've tried in order to redirect to the index function:
return Redirect::route('items.index', array($data['process_id']));
return Redirect::action('ItemsController#index', array($data['process_id']));
I've also tried using "with(...)"
The following (using either route or action) gives me a "route not defined" error:
return Redirect::action('process/'.$data['process_id'].'/items');
I don't think its good practice to recreate the view as in the index function. I should just be able to redirect and have done with it.
What am I doing wrong?
The model relatioships are as follows:
1 project hasmany items
1 item hasmany attributes
1 attribute hasmany extensions
controller source code
<?php
class ItemAttributesController extends \BaseController {
/**
* Display a listing of itemattributes
*
* #return Response
*/
public function index($item_id)
{
return $this->makeIndex($item_id);
}
/**
* Show the form for creating a new itemattribute
*
* #return Response
*/
public function create()
{
return View::make('item_attributes.create');
}
/**
* Store a newly created itemattribute in storage.
*
* #return Response
*/
public function store()
{
$validator = Validator::make($data = Input::all(), Itemattribute::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$attribute = Itemattribute::create($data);
// add created attribute id to sequence in the item for this attribute
$item = Item::findOrFail($attribute->item_id);
// get the sequence data
// append the attribute id
if (isset($item->attribute)){
$item->attribute = $item->attribute.', '.$attribute->id;
} else {
$item->attribute = $attribute->id;
}
$item->save();
return $this->makeIndex($data['item_id']);
}
/**
* Display the specified itemattribute.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$itemattribute = Itemattribute::findOrFail($id);
return View::make('item_attributes.show', compact('itemattribute'));
}
/**
* Show the form for editing the specified itemattribute.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$itemattribute = Itemattribute::find($id);
return View::make('item_attributes.edit', compact('itemattribute'));
}
/**
* Update the specified itemattribute in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$itemattribute = Itemattribute::findOrFail($id);
$validator = Validator::make($data = Input::all(), Itemattribute::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$itemattribute->update($data);
return $this->makeIndex($data['item_id']);
}
/**
* Remove the specified itemattribute from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$attribute = Itemattribute::findOrFail($id);
//find the item
$item = Item::findOrFail($attribute->item_id);
// get the sequence string
if (isset($item->attribute)){
// convert to array
$arr=explode(",",$item->attribute);
// remove item
if(($key = array_search($id, $arr)) !== false) {
unset($arr[$key]);
}
// convert back to string and replace initial string
$item->attribute = implode(",", $arr);
// save
$item->save();
}
ItemAttribute::destroy($id);
// return Redirect::route('item_attributes.index');
return $this->makeIndex($attribute->item_id);
}
private function makeIndex($item_id){
$item = Item::findOrFail($item_id);
$project = Project::findOrFail($item->project_id);
$item_attributes = DB::table('item_attributes')->where('item_id', $item->id)->get();
return View::make('item_attributes.index', compact('item_attributes', 'item', 'project'));
// return Redirect::to('item_attributes', );
}
}
routes source code
Route::get('/', function()
{
return View::make('home');
});
Route::resource('projects', 'ProjectsController');
Route::resource('items', 'ItemsController');
Route::resource('item_attributes', 'ItemAttributesController');
Route::resource('attribute_extentions', 'AttributeExtensionsController');
Route::get('project/{projects}/items', 'ItemsController#index');
Route::get('project/{projects}/item/create', 'ItemsController#create');
Route::get('item/{items}/item_attributes', array('as' => 'item_attributes', 'uses' => 'ItemAttributesController#index'));
Route::get('item/{items}/attribute_extentions', 'AttributeExtensionsController#index');
You are not using the route action correctly, it should point to the controller#function.
return Redirect::action('ItemsController#index', array('item_id' => 1));
Fixed it!
The solution was to use
return Redirect::to('item/'.$item->id.'/item_attributes');
This correctly passed the parameter in way that it could be picked up as a parameter by the function.
Thanks for all your help!

Models methods not detected by laravel in controller. Maybe a routing issue?

Due to my lack of experience with Laravel, I am having difficulty understanding why I can get the Post model variables but there are errors thrown when I try to call its methods. I don't know if it is a routing issue or not. This is based on a Laravel bootstrap starter site from Laravel starter site The following error and RegisteredUserController are as followed.
Call to undefined method stdClass::url()
$posts = DB::table('posts')->join('registered_posts' , 'posts.id' , '=' , 'registered_posts.post_id')->get();
foreach($posts as &$post){
echo $post->id; //works fine
echo $post->url(); //breaks
echo '<br>';
}
Here is the post model
<?php
use Illuminate\Support\Facades\URL;
class Post extends Eloquent {
/**
* Deletes a blog post and all
* the associated comments.
*
* #return bool
*/
protected $fillable = array('registered_post');
public function delete()
{
// Delete the comments
$this->comments()->delete();
// Delete the blog post
return parent::delete();
}
public function registered_post(){
return $this->registered_post;
}
/**
* Returns a formatted post content entry,
* this ensures that line breaks are returned.
*
* #return string
*/
public function content()
{
return $this->content;
}
/**
* Get the post's author.
*
* #return User
*/
public function author()
{
return $this->belongsTo('User', 'user_id');
}
/**
* Get the post's meta_description.
*
* #return string
*/
public function meta_description()
{
return $this->meta_description;
}
/**
* Get the post's meta_keywords.
*
* #return string
*/
public function meta_keywords()
{
return $this->meta_keywords;
}
/**
* Get the post's comments.
*
* #return array
*/
public function comments()
{
return $this->hasMany('Comment');
}
/**
* Get the date the post was created.
*
* #param \Carbon|null $date
* #return string
*/
public function date($date=null)
{
if(is_null($date)) {
$date = $this->created_at;
}
return String::date($date);
}
/**
* Get the URL to the post.
*
* #return string
*/
public function url()
{
return Url::to($this->slug);
}
/**
* Returns the date of the blog post creation,
* on a good and more readable format :)
*
* #return string
*/
public function created_at()
{
return $this->date($this->created_at);
}
/**
* Returns the date of the blog post last update,
* on a good and more readable format :)
*
* #return string
*/
public function updated_at()
{
return $this->date($this->updated_at);
}
}
Here are also the routes that I am using as well
Route::group(array('prefix' => 'registered', 'before' => 'auth'), function()
{
# Admin Dashboard
Route::post('registered', 'RegisteredUserController#getIndex');
Route::controller('/', 'RegisteredUserController');
});
Thank you in advance!
You are currently using the Query Builder but are expecting an Eloquent result. With DB::table your result will only consist of bare objects instead of models (with functions like url())
You can try this instead
$posts = Post::join('registered_posts' , 'posts.id' , '=' , 'registered_posts.post_id')->get();
You may also want to define the registered posts as relationship and then load it like that
$posts = Post::with('registeredPosts')->get();

Categories