Passing parameter / variable through two controllers in Laravel difficulty - php

I have a Data model that I want people to be able to view individual records of and then edit/add data to. I have managed to get the view route working;
Route::get('/data/{data_token}', 'DataController#show');
Data_token, is a unique string. This then uses this DataController function;
Public function show($data) {
$data = Data::where('data_token',$data)->first();
return view('data.show', compact('data'))
}
After which I can display the data on the page, and have a form for editing (actually its for adding data that doesn't exist, but whatever, same principle right).
On the form on the data.show view, I am sending it to a different view;
Route::get('/data/{data_token}/edit', 'DataController#edit');
This can use the $request variable to return the forms values, but I can't relate it to the data row I was previously editing?
how do I get the {data_token} passed to the edit function of the controller?
Edit( adding route files)
Noticed I forgot the {'data_token'} in the post route.
/Begs forgiveness

I think you've misunderstood how the routes and controllers work. What you're looking at is a fairly simple CRUD setup like the following;
Route::get('/data/{data_token}', 'DataController#show');
Route::get('/data/{data_token}/edit', 'DataController#edit');
Route::post('/data/{data_token}/edit', 'DataController#update');
Now your controller would have;
public function show($dataToken) { ... }
public function edit($dataToken) { ... }
public function update($dataToken, Request $request) { ... }
Then you'd have your form on the edit view like so;
<form action="{{ route('DataController#update') }}" method="post">
Laravels router will always try to pass in the URI variables as arguments to the methods provided.
Providing that I have understood what you need, this should suffice.

Related

Final Route URL Change Laravel 5.5

I am working on a school project. while working on a schools detail page I am facing an issue with the URL. My client needs a clean URL to run AdWords. My school detail page URL: http://edlooker.com/schools/detail/4/Shiksha-Juniors-Ganapathy. But he needs it like http://edlooker.com/Shiksha-Juniors-Ganapathy. If anyone helps me out it will be helpful, thanks in advance.
You need to define this route after all routes in your web.php (if laravel 5.x) or in routes.php (if it is laravel 4.2).
Route::get('{school}','YourController#getIndex');
And your controller should be having getIndex method like this,
public function getIndex($school_name)
{
print_r($school_name);die; // This is just to print on page,
//otherwise you can write your logic or code to fetch school data and pass the data array to view from here.
}
This way, you don't need to use the database to get URL based on the URL segment and you can directly check for the school name in the database and after fetching the data from DB, you can pass it to the school details view. And it will serve your purpose.
Check Route Model Binding section in docs.
Customizing The Key Name
If you would like model binding to use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model:
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
In this case, you will have to use one front controller for all requests and get data by slugs, for example:
public function show($slug)
{
$page = Page::where('slug', $slug)->first();
....
}
Your route could look like this:
Route::get('{slug}', 'FrontController#show');

Passing variable from backend to frontend laravel

I have 5 controllers and 5 models and they are all related to backend. I can easily output data in the backend but I need to that for the frontend as well. Not all of course but some of them.
For example I have controller called BooksController:
public function getBooks(Request $request)
{
$books = Books::all();
return view('backend.books.show', compact('images'));
}
So this will show it in backend without any problems but what I want is for example to loop through all the books and show their images in welcome.blade.php which doesn't have controller.
And also to pass other parameters to that same view from different controllers.
Is this is possible?
Thank you.
You are having an error because you did not declare the variable $image
public function getBooks(Request $request)
{
$books = Books::all();
$images = array_map(function($book) {
$book->image;
}, $books);
return view('backend.books.show', compact('images'));
}
It sounds like you are potentially caught up on some terminology. In this case, it sounds like backend is referring to your admin-facing interface, and frontend is referring to your user-facing interface.
You also seem to be locked on the idea of controllers. Unless the route is verrrrrry basic, create a controller for it.
Have a controller for your welcome view, for your admin view, basically (with some exceptions) a controller per resource or view is fine.
In this case, you would have one controller for your admin book view, and a seperate controller for your welcome view. Both of which would pull the books out of the db and render them in their own way

Adding in a variable via route with static route laravel

I want to be able to add a variable to a route that directs to a controller.
The only way I've seen it done is if the route itself is dynamic. However, in my case, I want a static url that will send a static variable to a controller. The reason for which is that there will be two static routes that will use the same controller in a different way via variables.
I am having trouble finding this in the documentation.
All I have found is this
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
I want to do the same but have {comment} and {post} but two variables is sent to the controllers.
Any help would be awesome!
Forexample:
Route::get('posts/{post}/comments/{comment}', ['as'=> 'viewComment', 'uses'=>'PostController#viewComment']);
Controller:
public function viewComment ($post, $comment)
{
dd($post.'/'.$comment);
}

pass user information in every function of the controller in laravel

I have a Controller witch contains more than 150 functions. almost all of the functions inside the controller are returning views.
each view should change if the user is logged in.
I almost handled this in the view side by using parent blades and etc. But in the controller side for almost every function i should check if the user is logged in and return some specific data about the user along with the view.
for example:
$user=[];
if(Auth::check())
{
$user=Auth::user;
$reputation=$user['reputation'];
$messages=$user->messages();
$notifications=$user->notification();
}
return view('pages.profile')->with(['user'=>$user , 'messages'=>$messages , 'notifications'=>$notifications]);
I thought that this is possible using middlewares but i could not figure it out.
what are the alternatives here?
for more information i am using laravel 5.
One solution could be using your custom function instead of view(). Sth like:
//in your controller action
public function someAction() {
return $this->view('pages.profile');
}
protected function view($template, $data = array()) {
return view($template)->with($data)->with([data that needs to be passed to all views]);
}

Laravel Routing to same view different function

I am trying to return values from a MySQL database into a datatable using Chumper. I am trying to obtain values from 2 tables; but I am having what I believe to be a routing issue as I do not know how to include 2 controller functions to the same view ie in my search view I want to render the result of 2 functions like : for a deeper understanding of what I am trying to accomplish see question : Laravel Chumper Datatable getting data into one datatable from multiple MySQL tables
Route::get('search', array('as' => 'instance.search', 'uses' => 'CRUDController#instances'));
Route::get('search', array('as' => 'accid.search', 'uses' => 'CRUDController#account_ids'));
any ideas ?
Only a single route will ever match any given URL requested of the system. I believe what Laravel will do is choose the second one (as in the second definition will overwrite the first).
You have some options here. All I can really tell from your question is that you want two methods to be executed when that route gets hit. This is indirectly possible, consider:
Route::get('search', 'MyController#instances');
class MyController extends Controller
{
public function instances()
{
$mydata = $this->account_ids();
$myotherdata = $this->getOtherData();
return View::make('myview')
->with('mydata', $mydata)
->with('myotherdata', $myotherdata);
}
private function getOtherData() { /* ... */ }
}
This isn't really clean, though, and eventually will lead to convoluted controller logic which is an anti-pattern in MVC. Fortunately, Laravel let's you use View Composers, which can greatly clean up your controller logic:
public function instances()
{
return View::make('myview');
}
Wow. Nice and simple. Now the view composer part:
// Inside of a service provider...
View::composer('search', 'App\Http\ViewComposers\AViewComposer');
use View;
class AViewComposer
{
public function compose(View $view)
{
$view->with('instances', $this->instances());
$view->with('accountIds', $this->accountIds());
}
public function instances()
{
// generate your instance data here and return it...
return $instances;
}
public function accountIds()
{
// generate your account id data here and return it...
return $accountIds;
}
}
You could take this a step further and inject another class into the constructor of this view composer to completely off-load the responsibility of determining what 'instances' and 'account ids' actually mean, should you need that same functionality elsewhere. This will help you keep your code extremely DRY.
You are having those 2 routes but with same domain so the second one is running over the second one.
Or you change the URL of on of them or you change the method for post instead of get

Categories