The following route works fine and the method can loop through the items:
http://localhost/library/api/books
$app->get('/api/books', 'Book:getBooks');
The class:
class Book {
:
:
public function __construct($container) {
$this->container = $container;
}
public function getBooks($request, $response) {
:
:
echo '{"book": ' . json_encode($books) . '}';
}
public function getBook($id) {
echo json_encode($id);
}
}
Calling the method with route pattern identified by 'id' as follows, returns nothing (empty $id):
http://localhost/library/api/books/10
$app->get('/api/books/{id}', 'Book:getBook');
It seems like 'id' won't pass.
How to handle correctly route pattern by identifier?
As I said in the comments, please let us know what the dev console says for instance in chrome under the category console and network.
I am not sure why you choose to create your routes like that, but I would create them following way (which also looks more tidy) :
Route::group(['prefix' => 'book'], function ()
{
Route::get('/', ['as' => 'index', 'uses' => 'BookController#index']);
Route::get('new', ['as' => 'new', 'uses' => 'BookController#new']);
Route::get('show/{bookID}', ['as' => 'show', 'uses' => 'BookController#show']);
Route::get('edit/{bookID}', ['as' => 'edit', 'uses' => 'BookController#edit']);
Route::post('create', ['as' => 'create', 'uses' => 'BookController#create']);
Route::post('update', ['as' => 'update', 'uses' => 'BookController#update']);
Route::delete('destroy/{deviceID}', ['as' => 'destroy', 'uses' => 'BookController#destroy']);
});
The BookController would look like this then:
class BookController extends Controller
{
// this shows all books and adds a pagination of 15 items, which you can easily increase or decrease
public function index()
{
$books = DB::table('books')->paginate(15);
return view('books.index', compact('books');
}
public function new()
{
$book = new Book;
return view('books.new', [
'books' => $books,
'type' => 'new'
]);
}
public function create(Request $request)
{
$this->validate($request, Book::$rules); // I put the rules inside of the Book Model, but you could just add them here aswell
$data = $request->all();
$book = new Book();
$book->fill($data);
if($book->save())
{
return redirect()->route('new')->with('success', 'success.');
}
else
{
return redirect()->route('new')->with('error', 'Error.')->withInput();
}
public function edit(Request $request, $bookID = 0)
{
$books = Book::all();
$newBook = new Book;
$book = Book::find($bookID);
if(is_null($book))
{
$books = Device::paginate(10); // paginate if you like to
return view('books.index', [
'books' => $books,
'errorNoBook' => 'No BOok'
]);
}
else
{
$bookID = $book->id;
}
return view('books.edit', [
'allBooks' => $allBooks,
'new' => $new,
'book' => $book,
]);
}
}
The following is a simple working solution that I found:
:
:
public function getBook($request, $response) {
$route = $request->getAttribute('route'); // route object
$id = $route->getArgument('id'); // route object identifier
$book = $this->db->table('books')->where('id', $id)->first();
echo json_encode($book);
}
Related
I have three TaskController function methods like this in My laravel application,
public function show($project_id,$task_id)
{
$project = Project::find($project_id);
$task = Task::find($task_id);
view('tasks.show')->withProject($project)->withFiles($files)->withTask($task);
return view('tasks.show', ['task' => $task, 'project' => $project]);
}
public function show1($project_id,$task_id)
{
$project = Project::find($project_id);
$task = Task::find($task_id);
view('tasks.show')->withProject($project)->withFiles($files)->withTask($task);
return view('tasks.show1', ['task' => $task, 'project' => $project]);
}
public function show2($project_id,$task_id)
{
$project = Project::find($project_id);
$task = Task::find($task_id);
view('tasks.show')->withProject($project)->withFiles($files)->withTask($task);
return view('tasks.show2', ['task' => $task, 'project' => $project]);
}
and my routes for this is like this,
Route::get('projects/{projects}/tasks/{tasks}',[
'uses' => '\App\Http\Controllers\TasksController#show',
]);
Route::get('collaborators/projects/{projects}/tasks/{tasks}', [
'uses' => '\App\Http\Controllers\TasksController#show1',
]);
Route::get('collaborators/projects/{projects}/tasks/{tasks}', [
'uses' => '\App\Http\Controllers\TasksController#show2',
]);
but among above three routes show1 route is not working. but if I delete show2 route then show1 is working. how can I fix this problem?
I have an url like /locations/name-of-the-location.ID
My route is:
Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => 'LocationsController#show'])->where([
'location' => '[0-9]+',
'slug' => '[a-z0-9-]+'
]);
Now I want to check if the slug provided is the same that is saved in the database column 'slug' with my model (because the slug may have changed). If not, then I want to redirect to the correct path.
Where is the best place to do that? I thought of \App\Providers\RouteServiceProvider- but when I try to use Route::currentRouteName() there, I get NULL, maybe because it is 'too early' for that method in the boot() method of RouteServiceProvider.
What I could do, is to work with the path(), but that seems a bit dirty to me, because I work with route prefixes in an other language.
Here's what I tried (I am using a little helper class RouteSlug) - of course it does not work:
public function boot()
{
parent::boot();
if (strstr(Route::currentRouteName(), '.', true) == 'locations')
{
Route::bind('location', function ($location) {
$location = \App\Location::withTrashed()->find($location);
$parameters = Route::getCurrentRoute()->parameters();
$slug = $parameters['slug'];
if ($redirect = \RouteSlug::checkRedirect(Route::getCurrentRoute()->getName(), $location->id, $location->slug, $slug))
{
return redirect($redirect);
}
else
{
return $location;
}
});
}
}
Your route should look like this:
Route::get('locations/{id}/{slug}', ['as' => 'locations.show', 'uses' => 'LocationsController#show'])->where([
'id' => '[0-9]+',
'slug' => '[a-z0-9-]+'
]);
And LocationsController#show should look like this:
public function show($id, $slug)
{
// Add 'use App\Location' to the top of this controller
$location = Location::find($id);
// I'm not sure what you were doing with the soft deleted items
// but you might want to restore them if you are using them
if ($location->trashed()) $location->restore();
if ($slug != $location->slug) {
return redirect()->route('locations.show', ['id' => $id, 'slug' => $location->slug]);
}
// Return the view
}
So finally I came up with a Middleware:
App\Http\Middleware\CheckSlug
public function handle($request, Closure $next)
{
if ($redirect = RouteSlug::checkRedirect(Route::currentRouteName(), $request->location->id, $request->location->slug, $request->slug))
{
return redirect($redirect);
}
return $next($request);
}
My route look like this:
Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => 'LocationsController#show'])->where([
'location' => '[0-9]+',
'slug' => '[a-z0-9-]+'
])->middleware(App\Http\Middleware\CheckSlug::class);
I do not understand the following problem.
Here are me routes:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
I can not create a new event, because when I click on the 'New Event' button, it uses EventController#view instead of EventController#newEvent.
Here is the EventController:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\EventModel;
class EventController extends Controller
{
public function index()
{
$events = EventModel::all();
return \View::make('event/index')->with('events', $events);
}
public function view($id)
{
return \View::make('event/view')
->with('event', EventModel::find($id));
}
public function newEvent()
{
dd("dd");
return \View::make('event/create');
}
public function create()
{
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->action('EventController#newEvent')
->withErrors($validator)
->withinput();
}
else
{
EventModel::create(array(
'title'=>Input::get('title'),
'start'=>Input::get('start'),
'end'=>Input::get('end'),
'userID'=>\Auth::user()->id,
));
//Session::flash('message', 'New event has been created!');
flash()->overlay('New event has been created!', 'Success');
return redirect()->back();
}
}
public function edit($id)
{
return \View::make('event/edit')
->with('event', EventModel::find($id));
}
public function update()
{
$event = EventModel::find(Input::get('event_id'));
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->back()
->withErrors($validator)
->withinput();
}
else
{
$event->title = Input::get('title');
$event->start = Input::get('start');
$event->end = Input::get('end');
$event->save();
//Session::flash('message', 'Successfully updated!');
flash()->overlay('Event has been sucessfully updated!', 'Success');
return redirect()->back();
}
}
public function destroy()
{
$id = Input::get('event_id');
dd("$id");
}
}
Why does this problem occur?
You have to sort your routes because laravel checks the order of the routes.
Try:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Laravel route checks in the order they were defined.
event/new_event and event/{id} both have same route structure and so it is going to view action.
Change the order -
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
My question is based on how I can pass the $searchResult in my Controller class so as I can use it to display the search result
This is my Controller
class SearchController extends Controller {
public function getHome($searchFor = null) {
$result = SearchPost::all();
return view('home', ['resulta' => $result]);
}
public function postSearch(Request $request) {
$this->validate($request, [
'searchString' => 'required|max:20|alpha',
]);
$searchFor = $request['searchString'];
//Connection with model(SearchPost) to search
$searchResult = SearchPost::search($searchFor);
return redirect()->route('home', ['searchFor' => $searchFor]);
}
}
Routes:
Route::get('/{searchFor?}', [
'uses' => 'SearchController#getHome',
'as' => 'home'
]);
Route::post('/search', [
'uses' => 'SearchController#postSearch',
'as' => 'search'
]);
Try the following methods:
return redirect(route('home', ['searchFor' => $searchFor]));
Or
return redirect('home')->with('home', ['searchFor' => $searchFor]);
i want to redirect to my thread show but something error and missing
here is my route
Route::get('forum/{forumthread}', [
'uses' => 'ForumController#show',
'as' => 'forum.show'
]);
Route::get('forum/{forumthread}/create', [
'uses' => 'ForumController#indexcreate',
'as' => 'forum.index.create'
]);
here is my controller
public function indexcreate($slug){
$forum = forumthread::where('slug', $slug)->first();
return view('forum.index.indexcreate', compact('forum'));
}
public function indexstore(Request $request, $slug){
$forumindex = new forumindex;
$forumindex->title = $request->title;
$forumindex->body = $request->body;
$forumindex->slug = EasySlug::generateSlug($forumindex->title, $separator = '-');
$forumindex->user_id = Auth::user()->id;
$forumindex->save();
return redirect()->route('forum.show', $forum->slug);
}
help me for this thank you
Have you tried to wrap the second argument of the route() function in array?
return redirect()->route('forum.show', ['slug' => $forum->slug]);
Here's the what the Laravel's documentation says:
If your route has parameters, you may pass them as the second argument
to the route method:
// For a route with the following URI: profile/{id}
return redirect()->route('profile', ['id' => 1]);
Try this
return redirect()->action('ForumController#show', array('slug'=>$forum->slug));