laravel can't retrieve session when redirect - laravel

in laravel 5.4
class AdminController extends Controller
{
public function checkLogin(Request $request)
{
Session::put('admin','yes');
return redirect('mobiles');
}
}
class MobilesController extends Controller
{
public function __construct()
{
if( ( Session::has('admin') ) )
{ dd('admin');}
else
{ dd('not admin'); }
}
}
it prints 'not admin' so what happen to the session , if i prints the admin session in class checkLogin it prints normally

Since L5.3, you cannot a access to the session in the controller's constructor. You have to use a closure :
public function __construct()
{
$this->middleware(function ($request, $next) {
echo Session::has('admin') ? 'admin' : 'not admin';
return $next($request);
});
}
https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors

you have to use laravel flashed-session-data
https://laravel.com/docs/5.4/redirects#redirecting-with-flashed-session-data
return redirect('mtest2')->with('admin','yes');
so modify your code like this
class AdminController extends Controller {
public function checkLogin(Request $request){
return redirect('mobiles')->with('admin',true);
}
}
class MobilesController extends Controller {
public function __construct() {
if( session()->has('admin') ){
dd('admin');
}else{
dd('not admin');
}
}
}
Here is updated code if you do not want to use Flashed data
class AdminController extends Controller {
public function checkLogin(Request $request){
$request->session()->put('admin',true);
return redirect('mobiles');
}
}
it should work.

Related

Resource Api laravel 9 return null

I have this project that uses Laravel 9 framework and I'm using resource Api method. It worked fine for index and store function but it returns null when it comes update, show ,delete methods. I have my code down below:
My Model:
class Re14 extends Model
{
use HasFactory;
protected $fillable=['re14002'];
}
My Migration:
return new class extends Migration
{
public function up()
{
Schema::create('re14s', function (Blueprint $table) {
$table->id();
$table->string('re14002');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('re14s');
}
};
MY Controller:
class Re14Controller extends Controller
{
public function index()
{
return Re14Resource::collection(Re14::all());
}
public function store(Re14Request $request)
{
$re14=Re14::create($request->validated());
return new Re14Resource($re14);
}
public function show(Re14 $re14)
{
return new Re14Resource($re14);
}
public function update(Re14Request $request, Re14 $re14)
{
$re14->update($request->validated());
return new Re14Resource($re14);
}
public function destroy(Re14 $re14)
{
$re14->delete();
return response("Deleted Successfully!");
}
}
MY Resource
public function toArray($request)
{
return [
'id'=>$this->id,
're14002'=>$this->re14002
];
}
}
My Request
class Re14Request extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
're14002'=>['required','string','unique:re14s,re14002']
];
}
}
MY Route
Route::apiResource('level',Re14Controller::class);
I use Postman to test my Api. It worked fine for index and store but got stack when it comes update, show, delete
{
"data": {
"id": null,
"re14002": null
}
}

How to share $request variable between other function from other url in same controller on laravel

I want to share $request variable between other function from other url in same controller on laravel like below but how ?
Controller
class ABCController extends Controller
{
public function validation(Request $request)
{
---------------
}
public function save()
{
Log::debug($request)
}
api.php
Route::post('/abc',[ABCController::class,'validation']);
Route::get('/save',[ABCController::class,'save']);
What I tried
class ABCController extends Controller
{
public function validation(Request $request)
{
Session::put('data', $request)
session(['data' => $request]);
Log::debug(Session::get('data'));
Log::debug(session('data'));
}
public function save()
{
Log::debug(Session::get('data'));
Log::debug(session('data'));
}
I tried above but Log::debug in save function show me null in log.
Please give me advice.
Create a global variable
class ABCController extends Controller
{
private $data;
public function validation(Request $request)
{
$this->data =$request;
}
public function save()
{
echo $this->data;
}
}

Testing Custom Route Model Binding

I'm trying to test a custom class that implements \Illuminate\Contracts\Routing\UrlRoutable and can't get the resolveRouteBinding method invoked.
<?php
namespace Tests\Unit;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class BindingExampleClassTest extends TestCase
{
function test_invoke_resolve_route_binding_method()
{
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
});
$this->get('/invoke-route-binding/1');
}
}
class BindingExampleClass implements \Illuminate\Contracts\Routing\UrlRoutable
{
public $id;
public function resolveRouteBinding($value, $field = null)
{
$this->id = $value;
}
public function getRouteKey()
{
// TODO: Implement getRouteKey() method.
}
public function getRouteKeyName()
{
// TODO: Implement getRouteKeyName() method.
}
public function resolveChildRouteBinding($childType, $value, $field)
{
// TODO: Implement resolveChildRouteBinding() method.
}
}
The dd response is BindingExampleClass with id still null.
Registering route inside a test function will not include any middleware. When working with route model binding in Laravel, \Illuminate\Routing\Middleware\SubstituteBindings::class middleware must be defined in the router instance.
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
})->middleware(\Illuminate\Routing\Middleware\SubstituteBindings::class);

Add function to laravel Notification

I have next Notification class:
class WelcomeNotification extends Notification
{
use Queueable;
public function __construct()
{
//
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
//
];
}
}
And I want add some function to this. For example:
public function myFunction()
{
return 'something';
}
But $user->notifications->first()->myFunction return nothing
When you call the notifications() relation it turns out is a polymorphic relation using the DatabaseNotification model. The proper way is to inherit DatabaseNotification and write the custom function their.
For example, create app/DatabaseNotification/WelcomeNotification.php and inherit DatabaseNotification model.
namespace App\DatabaseNotification;
use Illuminate\Notifications\DatabaseNotification;
class WelcomeNotification extends DatabaseNotification
{
public function foo() {
return 'bar';
}
}
And override the notifications() function that uses the Notifiable trait:
use App\DatabaseNotification\WelcomeNotification;
class User extends Authenticatable
{
use Notifiable;
...
public function notifications()
{
return $this->morphMany(WelcomeNotification::class, 'notifiable')
->orderBy('created_at', 'desc');
}
...
}
And now you can call the custom function as follows:
$user->notifications->first()->foo();

Laravel Multiple module using one Controller

Now I have few modules created like Product, Sale, Category. I found out they actually using same function with similar process. For example update() in Controller :
Category
public function update($id)
{
$instance = Category::findOrFail($id);
$instance->fill(Input::all())->save();
}
Product
public function update($id)
{
$instance = Product::findOrFail($id);
$instance->fill(Input::all())->save();
}
How can I join it together to BaseController by just make the Model dynamic?
Something like this:
abstract class ResourceController extends BaseController
{
protected $entity;
public function __construct(Model $entity){ //or Eloquent, depending on your import alias
$this->entity = $entity;
}
public function update($id)
{
$instance = $this->entity->findOrFail( $id );
$instance->fill( Input::all() )->save();
}
}
class ProductController extends ResourceController{
public function __construct(Product $entity){
parent::__construct($entity);
}
}
class CategoryController extends ResourceController{
public function __construct(Category $entity){
parent::__construct($entity);
}
}

Resources