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? - php

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!

Related

Laravel Changing Request data in Form Request Class

I'm processing a form with multiple date input which is not in A.D. For validation purpose i'm using Form Request.
Before validation and inserting in my database date input must be converted into A.D, so that i can do the proper validation & then if validation succeed date input is stored in A.D .
here is my code for converting date input in A.D
<?php
abstract class Request extends FormRequest
{
public function all()
{
$input = parent::all()
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
}
Now the problem is suppose you have failed validation and redirect back to the previous action and you then use old() or some other method to access the request data from the session, it will be modified, and i cannot get the the original data.
How can i change the date input in A.D when before validation so that i can properly validate in A.D and then store all the date input in A.D. by solving failed validation problem having modified input.
Edit Question
update:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\Contracts\CourseInterface;
use App\Repositories\Contracts\ClassInterface;
use App\Http\Requests\ClassRequest;
use App\Helpers\Helper;
class ClassController extends Controller
{
public function __construct(ClassInterface $class, CourseInterface $course)
{
$this->class = $class;
$this->course = $course;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$classes = $this->class->paginate();
return view('backend.class.index')->with([
'classes' => $classes
]);
/*return view('backend.class.index')->with([
'classes' => $classes
]);*/
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$courses = $this->course->all();
return view('backend.class.create')->with([
'courses' => $courses
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ClassRequest $request)
{
// dd($request->all());
$this->class->create($request->all());
return redirect()->route('classes.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$class = $this->class->find($id);
$courses = $this->course->all();
return view('backend.class.edit')->with([
'class' => $class,
'courses' => $courses
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(ClassRequest $request, $id)
{
$class = $this->class->update($request->all(), $id);
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->class->delete($id);
return redirect()->route('classes.index');
}
public function delete($id)
{
$class = $this->class->find($id);
return view('backend.class.delete')->with([
'class' => $class
]);
}
}
My class Request File
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Helpers\Helper;
class ClassRequest extends Request
{
public function all()
{
$input = parent::all();
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
//$this->sanitize();
switch($this->method())
{
case 'GET':
case 'DELETE':
{
return [];
}
case 'POST':
{
return [
'name' => 'required',
'course_id' => 'required',
'start_date' => 'required|date',
'end_date' => 'date|after:start_date',
];
}
case 'PUT':
case 'PATCH':
{
return [
'name' => 'required',
'course_id' => 'required',
'start_date' => 'required|date',
'end_date' => 'date|after:start_date',
];
}
default:break;
}
}
}
For validation purpose i need to change the date from B.S in A.D because laraval validation don't recognize B.S date. If i convert date in request file the problem is if validation fails i get the modified request back in form after redirect.
So how can i validate the date by converting it into A.D. The date in database table must be stored in A.D format for that i can use Accessors and Mutators the main problem is how to validate the data which user input in B.S format.
Edit After the suggestion i got
Thank you all for the suggestion, thank you very much for your help. One way i can validate is by making a custom validation rule as suggested. Right now i have another idea for making this work.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Helpers\Helper;
abstract class Request extends FormRequest
{
/**
* Sanitize input before validation
*
* #return array
*/
public function validator($factory)
{
return $factory->make(
$this->sanitizeInput(), $this->container->call([$this, 'rules']), $this->messages()
);
}
protected function sanitizeInput()
{
if (method_exists($this, 'sanitize'))
{
return $this->container->call([$this, 'sanitize']);
}
return $this->all();
}
/**
* Check for input having _date for converting it into AD
*
* #return array
*/
public function sanitize()
{
$input = $this->all();
foreach ($input as $key=>$value)
{
if (substr($key, -5) == "_date")
{
$input[$key] = Helper::convert_in_ad($value);
}
}
return $input;
}
}
By using the following code request data is not changed. And There will be no need for creating custom validation and this will be easy if i later decided to take date in A.D from user then changing every request file for updating validation rule wont be necessary.
What do you think about this?
As has been mentioned in the comments you should try and avoid editing the data in your FormRequest.
What you could do is define a new validation rule specifically for this: https://laravel.com/docs/5.3/validation#custom-validation-rules
So, in your app/Providers/AppServiceProvider (or another registered ServiceProvider) you could have something like:
Validator::extend('bs_date', function ($attribute, $value, $parameters, $validator) {
$date = date_parse(Helper::convert_in_ad($value));
return checkdate($date['month'], $date['day'], $date['year']);
}, 'Your error message');
Validator::extend('bs_after', function ($attribute, $value, $parameters, $validator) {
$data = $validator->getData();
$before = Helper::convert_in_ad($data[$parameters['0']]);
$after = Helper::convert_in_ad($value);
return (new \DateTime($before)) < (new \DateTime($after));
}, 'Your error message');
Rules
'start_date' => 'required|bs_date',
'end_date' => 'date|bs_after:start_date',
Obviously, don't forget to import Validator and Helper in the ServiceProvider.
This should mean that you don't have to edit your input anymore.
Hope this helps!

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

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();

Laravel-Bootstrap Starter Site content management

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).

Laravel Undefined Offset: 1 - cause by routing

I get the error when trying to make a post call to /api/subject/search
I assume it's a simple syntax error I'm missing
I have my api routes defined below
Route::group(array('prefix' => 'api'), function()
{
Route::post('resource/search', 'ResourceController');
Route::resource('resource', 'ResourceController');
Route::post('subject/search', 'SubjectController');
Route::resource('subject', 'SubjectController');
Route::resource('user', 'UserController');
Route::controller('/session', 'SessionController');
Route::post('/login', array('as' => 'session', 'uses' => 'SessionController#Store'));
});
And my controller is mostly empty
class SubjectController extends \BaseController
{
public function search()
{
$subjects = [];
if((int)Input::get('grade_id') < 13 && (int)Input::get('grade_id') > 8)
$subjects = Subject::where('name', 'like', '%HS%')->get();
else
$subjects = Subject::where('name', 'not like', '%HS%')->get();
return Response::json([
'success' => true,
'subjects' => $subjects->toArray()
]);
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
You need to specify the method.
try
Route::post('subject/search', 'SubjectController#search');
See the named route example:
Laravel Docs
In your case I think search is not resolved by the controller to load the search() method. You are also sending a POST for search functionality and I guess it's better to do a GET request since POST and PUT are for storing data.
Conventions
When creating API's it's a good thing to stick to naming conventions and patterns.
http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
Solution
Your route could be simpler like this: api.yourdomain.com/api/subject?search=term1,term2. Doing this with a GET query makes it going to the index() method. There you can check the GET params and do your search stuff and return.
Check this for the cleanest and truely RESTful way to make an API in Laravel:
How do I create a RESTful API in Laravel to use in my BackboneJS app
I got same error when accessing object at index of an empty array in view blade php file.

Categories